第八章、Vue3中的组件通信方式

  • Post author:
  • Post category:vue


示例: options API演示

一、父子组件通信:

props / emit

// parent.vue
<template>
   <Foo  :msg="msg" :state="state"  @modifyMsg="modifyMsg" />
</template>
 const msg = ref('Hello World')
 const modifyMsg = (val) =>{
   console.log(val) //  父组件接受子组件传递的数据  'Hello Coder'
    msg.value = val;
 }

// child.vue: emits选项可防止组件自身根组件原生事件监听,被触发两次问题,建议申明;
export default defineComponent({
  props:['msg','state'],   // 接受父组件传递的数据
  emits:['changeMsg'],     
  setup(props,{  attrs, slots, emit, expose }) {
    const changeMsg = () =>{
       emit('modifyMsg', 'Hello Coder')  // 向父组件派发事件,并传递参数
    }  
    return { changeMsg }
   }
})

expose / ref



版权声明:本文为weixin_42321326原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。