技术文摘
vue里$emit的使用方法
vue里$emit的使用方法
在Vue.js开发中,$emit 是一个非常重要的方法,它主要用于触发自定义事件,在组件通信中扮演着关键角色。掌握它的使用方法,能够极大地提升我们开发效率与代码的可维护性。
在父子组件通信场景下,$emit 常用于子组件向父组件传递数据或通知父组件执行某些操作。在子组件中定义一个方法,在该方法内部使用 $emit 触发一个自定义事件。例如:
<template>
<button @click="sendMessage">点击</button>
</template>
<script>
export default {
methods: {
sendMessage() {
this.$emit('child-event', '这是子组件传递的数据');
}
}
}
</script>
上述代码中,当按钮被点击时,sendMessage 方法被调用,$emit 触发了名为 'child-event' 的自定义事件,并传递了一个字符串数据。
然后,在父组件中监听这个自定义事件。在父组件的模板中引入子组件,并添加监听:
<template>
<child-component @child-event="handleChildEvent"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleChildEvent(data) {
console.log(data);
}
}
}
</script>
这样,当子组件触发 'child-event' 事件时,父组件的 handleChildEvent 方法就会被调用,并且接收到子组件传递过来的数据。
$emit 也可用于兄弟组件之间的通信。这种情况下,我们需要创建一个事件总线(Event Bus)。先创建一个全局的Vue实例作为事件总线:
import Vue from 'vue';
export const eventBus = new Vue();
在发送数据的组件中,引入事件总线并使用 $emit 触发事件:
<template>
<button @click="sendDataToBrother">发送数据</button>
</template>
<script>
import { eventBus } from './eventBus.js';
export default {
methods: {
sendDataToBrother() {
eventBus.$emit('brother-event', '来自兄弟组件的数据');
}
}
}
</script>
在接收数据的组件中,引入事件总线并监听事件:
<template>
<div></div>
</template>
<script>
import { eventBus } from './eventBus.js';
export default {
created() {
eventBus.$on('brother-event', (data) => {
console.log(data);
});
}
}
</script>
通过这种方式,实现了兄弟组件之间的通信。$emit 为Vue组件间的通信提供了强大的支持,熟练运用它能让我们的Vue项目开发更加得心应手。
TAGS: Vue组件通信 vue_emit使用 $emit原理 $emit实践
- 消息中间件深度系列:异构消息队列海量数据流转 Connect 架构剖析
- ISTIO 服务网格浅析
- 前端新手引导功能的实现之道
- 自回归滞后模型用于多变量时间序列预测
- 面试阿里后的感慨:TCC 分布式事务原理必须搞清楚
- Spring 框架的介绍与运用
- 为何总弄不懂 Java IO 流?此乃我用过的绝佳工具
- 你的团队究竟处于王者还是青铜段位(上)
- 阿里面试官竟问分布式事务如何实现高可用
- 常见的十个 JavaScript 问题
- Spring Security 中 RememberMe 登录的轻松实现
- Spring Boot 3.0 正式推出,此升级指南务必收藏
- 10 万吸引大佬分享写论文的 10 大技巧,连与审稿人沟通都涵盖
- 谈谈装饰者模式
- 【详解 Go Slice 之 Cap 读者称终于理解】