• 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>
  • 相关阅读:
    2019 滴滴java面试笔试总结 (含面试题解析)
    2019 阿里java面试笔试总结 (含面试题解析)
    Mangos笔记
    Google 多源码管理工具 gclient
    构建系统介绍
    Ninja介绍
    小试 Ninja
    如何使用Ninja快速编译LLVM和Clang
    FMS4中的P2P功能
    Flex之HTML5视频播放解决方案
  • 原文地址:https://www.cnblogs.com/yixiongqiang/p/16257666.html
Copyright © 2020-2023  润新知