vue3中的组件通讯

父子通讯

最常用的父子间通讯方法,

1:父传子数据:defineProps接收

2:子传父方法:defineEmits抛出

3:ref,在父组件中,使用ref,调用子组件的方法

具体使用方法,看以下栗子:

子组件 child.vue

<button @click="giveParentMenthed">把这个方法抛到父组件</button>
<script setup>
   import {defineEmits} from 'vue'
 
   父传子中,子组件接收的参数的方法
   const prop =defineProps({
      data:{
          type:String,
          default:""
      }
   })
   子传父:的方法  
  const emit = defineEmits(['ParentMenthed']); //因为vue3中,遵循按需引入,所以defineEmits在使用时需要引入
  const giveParentMenthed=()=>{   
     emit(
'ParentMenthed','这是子组件跑出来的点击事件,给父组件的数据')   
  }

  这是让父组件使用ref调用的一个方法
   const refClick = () => {
      console.log("这是父组件使用ref来触发的事件");
   };
   注:这里要注意,在script中使用了setup语法糖的话,一定要使用defineExpose这个方法,将,方法抛出去,否则父组件用不了
   defineExpose({
      refClick
   });
</script>

父组件 parent.vue

<child ref='childRefs' :data="childD" @ParentMenthed="giveParentMenthed"></child>
 <button @click="refClickBtn">使用ref获取子组件方法</button>
<script setup>
  import child from './child.vue' //引入子组件

   父传子的数据
   const childD=ref('这是父组件传过来的')
 
  子传父跑出来的方法
   const giveParentMenthed=(msg:any)=>{
      console.log(msg) //console:‘这是子组件跑出来的点击事件,给父组件的数据’
   }
 
   使用ref调用子组件的方法
    const childRefs = ref();
   const refClickBtn = () => {
      console.log(childRefs.value)
      childRefs.value.refClick();
   };
</script>

 

posted @ 2022-05-11 13:55  衣兄先生  阅读(151)  评论(0编辑  收藏  举报