emits 指令用于在 Vue 组件中声明自定义事件,以便子组件向父组件传递数据或触发动作。在子组件中使用 emits 定义事件,在父组件中使用 @ 事件监听器来侦听这些事件。可以传递参数和使用别名为子组件中更简洁的语法。最佳实践包括使用唯一的事件名称、避免传递大量数据以及使用 v-on 而不是 $on 侦听事件。

Vue 中 emits 的用法
emits 指令用于在 Vue 组件中声明自定义事件,允许子组件向父组件传递数据或触发动作。
基本用法
在子组件中使用 emits 定义事件:
立即学习“前端免费学习笔记(深入)”;
export default {
emits: ['update-count'],
data() {
return {
count: 0
};
},
methods: {
incrementCount() {
this.count++;
this.$emit('update-count', this.count);
}
}
};在父组件中监听事件:
传递参数
可以通过 emits 传递参数,就像在普通 JavaScript 事件中一样:
// 子组件
this.$emit('update-count', this.count, 'Custom data');
// 父组件
handleUpdateCount(count, customData) {
console.log('Count updated to:', count);
console.log('Custom data:', customData);
}使用别名
为了在子组件中使用更简洁的语法,可以使用别名:
// 子组件
emits: {
updatedCount: 'update-count'
}
// 父组件
最佳实践
- 对于每个事件使用唯一的名称。
- 避免在事件中传递大量数据,而是通过 props 或共享状态。
- 在子组件中使用
v-on侦听事件,而不是$on。










