vue 中 $emit(key,value) 的作用
在 Vue.js 中,$emit() 方法用于触发父组件传入的事件,实现子组件向父组件传值。
语法
<code class="javascript">this.$emit('event-name', 'argument');</code>作用
使用方法
立即学习“前端免费学习笔记(深入)”;
v-on 指令监听事件:<code class="html"><Child @custom-event="handleEvent"></Child></code>
this.$emit() 触发事件并传递参数:<code class="javascript">// 子组件
export default {
methods: {
handleClick() {
this.$emit('custom-event', '数据');
},
},
};</code>handleEvent 方法来接收并处理子组件传递的数据:<code class="javascript">// 父组件
methods: {
handleEvent(data) {
// 处理子组件传递的数据...
},
},</code>示例
<code class="html"><!-- 父组件 -->
<template>
<Child @data-changed="receiveData"></Child>
</template>
<script>
export default {
methods: {
receiveData(data) {
console.log(`从子组件接收的数据:${data}`);
},
},
};
</script>
<!-- 子组件 -->
<template>
<button @click="sendData">发送数据</button>
</template>
<script>
export default {
methods: {
sendData() {
this.$emit('data-changed', '这是从子组件传递的数据');
},
},
};
</script></code>以上就是vue中$emit(key,value)的作用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号