vue3父组件方法之间方法的互相调用

场景描述

在项目开发中。我们可能会使用父组件调用子组件中的方法
也有可能子组件中调用父组件中的方法
下面我们来看一看组件之间方法调用

父组件页面

<template>
  <div>
    <list-com ref="listRef"></list-com>
    <button @click="changeValue" >改变值</button>
  </div>
</template>
<script>
import listCom from "@/components/list-com.vue"
import { ref } from '@vue/reactivity'
export default {
  components:{
    listCom
  },setup () {
    let listRef=ref()
    function changeValue(){
      // 需要注意let listRef=ref() 不能够写在这函数体内,
      // 否者listRef 将会找不到,因为有函数作用域
      listRef.value.fatherMess([{name:'杨洋'}])
    }
    return {changeValue,listRef}
  }
}
</script>

子组件页面

<template>
    <div>
        <h2>我是子组件</h2>
         儿子接受到的数据:{{ list.arr}}
    </div>
</template>

<script>
import { reactive } from '@vue/reactivity';
export default {
    setup () {
        let list=reactive({
            arr:[]
        })
        function fatherMess(mess){
            console.log('父组件给子组件的值',mess );
            list.arr=mess
        }
        // 虽然页面上没有使用这个函数,
        // 但是也要抛出去,否者父组件会报错 fatherMess is not a function 
        return {fatherMess,list}
    }
}
</script>

出现 Uncaught TypeError: listRef.value.fatherMess is not a function 如何解决

出现这样的错误,是因为子组件中的事件 fatherMess函数。
并没有抛出出去哈
解决办法 子组件中  return {fatherMess}

子组件调用父组件中的方法

子组件

<template>
    <div>
        <h2>我是子组件</h2>
        <button @click="getHander" >获取值</button>
    </div>
</template>
<script>
import { reactive } from '@vue/reactivity';
export default  {
    setup (props,{attrs,slots,emit}) {
        function getHander(){
            // 不能够在使用原来的 this.$partent.xxx()这种方式了
            emit('myclick','给父组件的值' )
        }
        return {getHander}
    }
}
</script>

父组件

<template>
  <div>
    <list-com  @myclick="myclick"></list-com>
  </div>
</template>

<script>
import listCom from "@/components/list-com.vue"
export default {
  components:{
    listCom
  },setup () {
    function myclick(mess){
      console.log(mess);
    }
    return {myclick}
  }
}
</script>

相关文章

这篇文章我们将通过debug源码的方式来带你搞清楚defineAsync...
欧阳老老实实的更新自己的高质量vue源码文章,还被某2.6k st...
前言 在Vue3.5版本中响应式 Props 解构终于正式转正了,这个...
组合式 (Composition) API 的一大特点是“非常灵活”,但也因...
相信你最近应该看到了不少介绍Vue Vine的文章,这篇文章我们...
前言 在欧阳的上一篇 这应该是全网最详细的Vue3.5版本解读文...