Vue3.js调用父组件的方法

在Vue2中,通常使用this.$emit调用父组件的方法。但在Vue3中,由于setup函数在beforeCreate和created之前执行,this未绑定,因此不能直接使用this.$emit。解决办法是通过setup的第二个参数context访问emit。子组件可以通过context.emit(eventFuction,10)来调用父组件的eventFuction方法。
摘要由CSDN通过智能技术生成

Vue2的时候一直使用this.$emit('方法名','参数')的方式, 调用父组件的方法. 是没有问题的.

Vue3的时候, 假如我们父组件的方法放在setup()函数中, 子组件是无法获取通过this.$emit()调用父组件的方法.

举例代码如下

父组件 Father.vue

<template>
  <Child
    @eventFuction="eventFuction"
  >
  </Child>
</template>

<script>
import { defineComponent } from 'vue'
import Child from "./Child.vue";
export default defineComponent({
  name: "Father",
  components: {
    Child,
  },
  setup() {
    // 父组件声明的方法
    const eventFuction = (param) =>{
      console.log(param, '接收子组件传值');
    }
    return {
      eventFuction,
    }
  }
})
</script>

<style scoped>
</style>

子组件 Child.vue

<template>
  <a-button @click="onClick">调用父组件方法传参</a-button>
</template>

<script>
import { defineComponent } from 'vue'
export default defineComponent({
  name: "Child",
  setup() {
    const onClick = ()=> {
      // 这样是会报错的 
      this.$emit('eventFuction ', '10')
    }
    return{
      onClick,
    }
  }
})
</script>

<style scoped>

</style>

原因分析

在vue3中setup是在声明周期beforeCreate和created前执行, 这时候vue对象还没有创建, 所以我们无法使用this

解决办法

子组件的setup()函数中有个context的参数,这个参数中包含了emit的方法. 配合这个我们可以调用父组件的方法, 子组件修改后代码如下:

<template>
  <a-button @click="onClick">调用父组件方法传参</a-button>
</template>

<script>
import { defineComponent } from 'vue'
export default defineComponent({
  name: "Child",
  setup(props, context) {
    const onClick = ()=> {
      // 这样写就没问题了
      context.emit('eventFuction ', '10')
    }
    return{
      onClick,
    }
  }
})
</script>

<style scoped>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值