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>