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);
}
}
};
登录后复制
在父组件中监听事件:
<template><child></child></template><script>
import Child from './Child.<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15721.html" target="_blank">vue';
export default {
components: { Child },
methods: {
handleUpdateCount(count) {
console.log('Count updated to:', count);
}
}
};
</script>
登录后复制
传递参数
可以通过 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'
}
// 父组件
<template><child></child></template>
登录后复制
最佳实践
- 对于每个事件使用唯一的名称。
- 避免在事件中传递大量数据,而是通过 props 或共享状态。
- 在子组件中使用 v-on 侦听事件,而不是 $on。
以上就是vue中emits的用法的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:木子,转转请注明出处:https://www.dingdanghao.com/article/475202.html
