
vue3 + element-plus, this.$emit失效,为什么?
问题描述
在 vue3 + element-plus 中,子组件使用 this.$emit 向父组件发送消息,但在父组件中无法收到。
分析和解决
根据提供的代码,可以发现以下问题:
1. 子组件的事件名不正确
子组件中使用 this.$emit("conditionupdate") 触发自定义事件,但父组件的事件监听器却是 "update"。两者名称不一致导致消息发送失败。
立即学习“前端免费学习笔记(深入)”;
2. 子组件未注册事件
父组件需要在渲染子组件时注册事件监听器,才能接收子组件发送的消息。
修改后的代码
子组件
zuojiankuohaophpcnscriptyoujiankuohaophpcn
import {ref} from 'vue';
export default {
name: 'newnew',
props: ['column', 'column_filter_type', 'select_items'],
data() {
return {
open_flag: ref(true),
condition: {
value_start: '',
value_end: ''
}
}
},
methods: {
confirm() {
this.open_flag = false;
// ...这里应该依据条件类型做校验
this.$emit('update', {
column: this.column,
column_filter_type: this.column_filter_type,
condition: this.condition
});
}
}
}
zuojiankuohaophpcn/scriptyoujiankuohaophpcn父组件
zuojiankuohaophpcnnewnew
...
@update="conditionUpdate" // 注册事件监听器
/youjiankuohaophpcn通过以上修改,子组件可以正确向父组件发送消息,从而触发父组件中的 conditionupdate 方法。










