文章目录
1.事件总线(eventBus)
定义
vue实例赋值给一个变量,就是中央事件总线
var bus=new Vue();
用途
实现跨组件传输
原理
将eventBus作为连接组件之间的桥梁,所有组件共用相同的事件中心,
向事件中心发送或接收事件,并可以通知其他组件;
2.eventBus使用步骤
1、初始化,创建一个事件总线并导出,以便其他模块可以使用并监听它;
// eventBus.js
import Vue from 'vue'
//通过一个空的Vue实例作为中央事件总线(事件中心)
export const EventBus = new Vue()
2、导入eventBus,使用$emit
发送数据;
3、导入$on
,使用$on
接收数据;
4、如果想移除事件,可以先导入eventBus,通过$off
移除;(eventBus.$off ( 'add', {} ))
3.在HTML网页中使用事件总线:模拟公众号和用户之间信息的发送和接收
代码
<div id="app">
<weixinauthor></weixinauthor>
<weixinuser></weixinuser>
</div>
<script>
// 1.初始化:创建一个事件总线
var bus = new Vue;
Vue.component('weixinauthor', {
template: `<div style="background:blue">
我是微信公众号:
<input type="text" ref="mytext">
<button @click="handleClick">发布</button>
</div>`,
methods: {
handleClick() {
// 2.导入eventBus,使用$emit发送数据:weixinmessage要保持一致
bus.$emit("weixinmessage", this