vue 中 $emit(key,value) 的作用
在 Vue.js 中,$emit() 方法用于触发父组件传入的事件,实现子组件向父组件传值。
语法
<code class="javascript">this.$emit('event-name', 'argument');</code>- event-name:要触发的事件名称,由父组件传入。
- argument:要传递给父组件的任意值。
作用
- 子组件向父组件传值:子组件通过 $emit() 发送事件,并将数据作为事件参数传递给父组件。
- 实现父子组件通信:$emit() 允许子组件主动触发事件,从而与父组件进行通信。
- 定制化事件处理:父组件可以监听子组件触发的特定事件,并执行相应的处理逻辑。
使用方法
立即学习“前端免费学习笔记(深入)”;
- 在父组件中,使用
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>










