vue3 子调用父中的方法

原文地址:

vue3.0 子组件调用父组件中的方法_普通网友的博客-CSDN博客_vue3子组件调用父组件的方法

在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 是想要调用父组件的一个方法

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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值