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

Vue 中 emits 的用法
emits 指令用于在 Vue 组件中声明自定义事件,允许子组件向父组件传递数据或触发动作。
基本用法
在子组件中使用 emits 定义事件:
立即学习“前端免费学习笔记(深入)”;
<code class="javascript">export default {
emits: ['update-count'],
data() {
return {
count: 0
};
},
methods: {
incrementCount() {
this.count++;
this.$emit('update-count', this.count);
}
}
};</code>在父组件中监听事件:
<code class="javascript"><template>
<Child @update-count="handleUpdateCount" />
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child },
methods: {
handleUpdateCount(count) {
console.log('Count updated to:', count);
}
}
};
</script></code>传递参数
可以通过 emits 传递参数,就像在普通 JavaScript 事件中一样:
<code class="javascript">// 子组件
this.$emit('update-count', this.count, 'Custom data');
// 父组件
handleUpdateCount(count, customData) {
console.log('Count updated to:', count);
console.log('Custom data:', customData);
}</code>使用别名
为了在子组件中使用更简洁的语法,可以使用别名:
<code class="javascript">// 子组件
emits: {
updatedCount: 'update-count'
}
// 父组件
<template>
<Child @updatedCount="handleUpdateCount" />
</template></code>最佳实践
v-on 侦听事件,而不是 $on。以上就是vue中emits的用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号