vue3 中,父子组件如何通信

子组件

component-a

component-a 暴漏方法,供外部调用

<template>
  <div class="com-a" @click="onClose"></div>
</template>


<script setup>

const emits = defineEmits([
  'close'
])

function notify() {
  console.log('click')
}

function onClose() {
  emits('close')
}

defineExpose({
  notify // 暴漏的方法
})
</script>

  • 子组件对外暴露了 notify 事件,供父组件调用
  • 子组件触发了 close 事件,供父组件接收

父组件

component-b

调用 component-a 组件中的方法

<template>
  <component-a ref="comRef" @close="onClose"></component-a>
</template>

<script setup>

const comRef = ref();


onMounted(() => {

  const instance = comRef.value;

  if(typeof instance?.notify === 'function') {
    instance.notify()
  }
})

function onClose() {
  console.log('父组件方法被调用')
}

</script>
  • 父组件主动调用 notify 方法
  • 父组件接收 close 回调方法
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3父子组件通信有以下三种方式: 1. 父组件给子组件传参: 父组件通过props向子组件传递数据,子组件通过props接收数据。 2. 子组件调用父组件的方法: 父组件通过v-on绑定一个方法,子组件通过$emit触发这个方法,并传递数据。 3. 子组件暴露属性给父组件: 子组件通过defineExpose暴露属性或方法,父组件通过ref获取子组件实例,再调用子组件的属性或方法。 以下是三种方式的代码示例: 1. 父组件给子组件传参: 父组件: ```vue <template> <child-component :message="msg"></child-component> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, data() { return { msg: 'Hello World', }; }, }; </script> ``` 子组件: ```vue <template> <div>{{ message }}</div> </template> <script> export default { props: { message: String, },}; </script> ``` 2. 子组件调用父组件的方法: 父组件: ```vue <template> <child-component @change-visible="handleChangeVisible"></child-component> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, methods: { handleChangeVisible(visible) { console.log(visible); }, }, }; </script> ``` 子组件: ```vue <template> <button @click="handleClick">Change Visible</button> </template> <script> export default { methods: { handleClick() { this.$emit('change-visible', false); }, }, }; </script> ``` 3. 子组件暴露属性给父组件: 子组件: ```vue <template> <div>{{ message }}</div> </template> <script> import { defineExpose } from 'vue'; export default { setup() { const message = 'Hello World'; defineExpose({ message, }); return { message, }; }, }; </script> ``` 父组件: ```vue <template> <child-component ref="child"></child-component> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, mounted() { console.log(this.$refs.child.message); }, }; </script> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值