• 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>
  • 相关阅读:
    saxbuilder用法
    【转】开篇python--明白python文件如何组织,理解建立源文件
    [转]linux awk命令详解
    sed 指定行范围匹配(转)
    MySQL Error Code文档手册---摘自MySQL官方网站
    java文件读写操作大全
    详解coredump
    Java中Map根据键值(key)或者值(value)进行排序实现
    java如何对map进行排序详解(map集合的使用)
    遍历Map的四种方法
  • 原文地址:https://www.cnblogs.com/yixiongqiang/p/16257666.html
Copyright © 2020-2023  润新知