在vue2中,子组件调用父组件,直接使用this.$emit()即可。

但是在vue3中,很显然使用this.$emit() 已经开始报错了,为什么会报错呢?

原因是:在vue3中setup是在声明周期beforeCreate和created前执行,此时vue对象还未创建,因此我们无法使用this。

那么我们在vue3中,子组件该如何调用父组件的函数呢?

方法一:

首先写一个 Child.vue,重点在 setup 函数中引入 context 形参,配合 emit 使用。定义了两个函数,toFatherNum(), toFatherObject() 分别向父组件传递数字和对象

<template>
  <a-button @click="toFatherNum">子传父数字</a-button>
  <a-button @click="toFatherObject">子传父对象</a-button>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: "Child",
  setup(props, context) {
    function toFatherNum() {
      context.emit('eventIsNum', 888)
    }
    function toFatherObject() {
      context.emit('eventIsObject', { keyName: 'I am value' })
    }
    return{
      toFatherNum,
      toFatherObject,
    }
  }
})
</script>

<style scoped>

</style>


然后是 Father.vue,通过事件名称 eventIsNum 和 eventIsObject 接收子组件传递的值

<template>
  <Child
    @eventIsNum="receiveChildNum"
    @eventIsObject="receiveChildObject"
  >
  </Child>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import Child from "./Child.vue";
export default defineComponent({
  name: "Father",
  components: {
    Child,
  },
  setup() {
    function receiveChildNum(e: number) {
      console.log(e, '接收子组件数字');
    }
    function receiveChildObject(e: object) {
      console.log(e, '接收子组件对象');
    }
    return {
      receiveChildNum,
      receiveChildObject,
    }
  }
})
</script>

<style scoped>

</style>


方法二:
1.在子组件里引入useContext
import { useContext } from "vue";
2.获取上下文
const ctx = useContext();
3.在需要调用父组件的地方写上下面的代码进行调用
ctx.emit(‘fatherMethod’); //fatherMethod 是想要调用父组件的一个方法

方法一和二 供大家随意挑选哦!如果大家有更好的方法,欢迎大家评论留言或私信。
希望大家一起进步哟。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐