10-Vue基础-组件通信之事件总线 - cculin
组件通信之事件总线
1. 事件总线bus
使用全局事件总线,完成非父子组件之间的传值:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<component-a></component-a>
<component-b></component-b>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 定义全局中央事件总线
var bus = new Vue();
// 将事件总线绑定到全局属性prototype上,这样就能全局调用了
Vue.prototype.$bus = bus;
// 定义非父子组件A
Vue.component(\'component-a\', {
template: `
<div>
<p>我是来自组件 A 的内容</p>
<input type="text" v-model="mymessage" @input="passData(mymessage)">
</div>
`,
data() {
return {
mymessage: \'hello brother1\'
}
},
methods: {
passData(val) {
this.$bus.$emit(\'globalEvent\', val);
}
}
});
// 定义组件B
Vue.component(\'component-b\', {
template: `
<div>
<p>我是来自组件B的内容</p>
<p>组件A传递过来的数据:{{ brothermessage }}</p>
</div>
`,
data() {
return {
mymessage: \'hello brother2\',
brothermessage: \'\'
}
},
mounted() {
// 监听全局总线事件
this.$bus.$on(\'globalEvent\', (val) => {
// 获取监听的数据,并更新本地缓存
this.brothermessage = val;
});
}
});
var app = new Vue({
el: \'#app\'
});
/*
* 总结:1. 先定义一个全局总线事件,并绑定到全局事件属性上;
* 2. 创建组件A,并定义一个处理方法,绑定监听事件,并将数据传递过去;
* 3. 创建组件B,监听事件,并将传递的数据缓存到本地,方便业务逻辑调用。
* */
</script>
</body>
</html>