Vue中组件通信:父传子ref

Vue2中:

$ref

引用信息会注册在父组件的$refs对象上

父组件:

<template>
  <div id="app">
    <TodoItem ref="msg"></TodoItem>
    <p ref="dom"></p>
  </div>
</template>

<script>
import TodoItem from './components/so.vue'

export default {
  name: 'App',
  components: {
    TodoItem
  },
  mounted() {
    console.log(this.$refs)
    // 通过这种方法给子组件传递数据
    this.$refs.msg.getmsg("我是tc") // this.$refs.msg指向的是子组件的实例
    console.log(this.$refs.msg.msg)
    this.$refs.dom.innerHTML = "我是普通元素"
  },
  data() {
    return {
      
    }
  },
}
</script>

<style>
#app {
  margin: 20px auto 20px 20px;
}
</style>

子组件:

<template>
    <div class="so">
        <p>{{ msg }}</p>
    </div>
</template>

<script>
export default {
    name: "todo-item",
    data() {
        return {
            msg: ''
        }
    },
    methods: {
        getmsg(s) {
            this.msg = s
        }
    }
}
</script>

<style scoped>

</style>

 Vue3中:

vue3中需要引入defineExpose从子组件向父组件暴露需要获取到的对应的变量或方法

在父组件中可以使用ref="(el) => child = el"的方式来准确获取到子组件的实例,然后使用child.value.(对应方法名或变量名)的方式获取相应信息

父组件:

<template>
  <TodoItem :ref="(el) => child = el"></TodoItem>
  <p ref="dom"></p>
</template>

<script>
import TodoItem from './components/so'
import { ref, onMounted  } from 'vue'

export default {
  name: 'App',
  components: {
    TodoItem
  }
}
</script>

<script setup>
  const child = ref(null)
  // const msg = ref()
  const dom = ref()
  onMounted(() => {
    console.log(child.value.getmsg("我是tc"))
    // msg.value.getmsg("我是tc")
    dom.value.innerHTML = "我是一个普通的DOM元素"
  })
</script>

<style>
#app {
  margin: 20px auto 20px 20px;
}
</style>

子组件:

<template>

  <div class="so">
    <p>{{ msg }}</p>
  </div>

</template>

<script>
import { ref, defineExpose } from 'vue'
export default {
    name: "todo-item",
}
</script>

<script setup>
const msg = ref("")
const getmsg = (s) => {
  msg.value = s
}
// 想要父组件可以获取到需要使用defineExpose向父组件暴露
defineExpose({getmsg})
</script>
<style scoped>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值