1.中央事件总线
- 实质就是创建一个vue实例,通过一个空的
vue 实例作为桥梁实现 vue 组件间的通信。它是实现非父子组件通信的一种解决方案。
- 1.创建一个
bus 的 vue 实例
- 2.在组件
B 的生命周期 created 中,通过对 bus 使用 $on 去绑定一个 add 的
- 3.在
A 组件中的 handle 方法中,通过对 bus 使用 $emid 方法去触发
- 其他方式的例子请参考例子: www.cnblogs.com/singerlee-c…
<!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">
<App></App>
</div>
//js部分
<script src="./vue.js"></script>
<script>
const bus = new Vue();
Vue.component('B', {
data() {
return {
count: 0
}
},
template: `
<div>{{count}}</div>
`,
created(){
bus.$on('add',(n)=>{
this.count+=n;
})
}
})
Vue.component('A', {
data() {
return {
}
},
template: `
<div>
<button @click='handleClick'>加入购物车</button>
</div>
`,
methods:{
handleClick(){
bus.$emit('add',1);
}
}
})
const App = {
data() {
return {
}
},
template: `
<div>
<A></A>
<B></B>
</div>
`,
}
new Vue({
el: '#app',
data: {
},
components: {
App
}
})
</script>
</body>
</html>
2.中央事件总线在脚手架中的应用
- 新建一个
vue-bus.js 文件,用来创建一个vue实例让后导出
const change = function (Vue){
const Bus = new Vue({
methods: {
emit(event, ...args) {
this.$emit(event, ...args);
},
on(event, callback) {
this.$on(event, callback);
},
off(event, callback) {
this.$off(event, callback);
}
},
});
Vue.prototype.$bus=Bus;
}
export default change;
- 之后在
main.js 中引入 vue-bus.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Change from "./components/vue03/vue-bus"
Vue.use(Change);
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
<template>
<div @click="testSend(msg)">我是子组件1</div>
</template>
<script>
export default {
data() {
return {
msg: "gogogog"
}
},
methods: {
testSend(val) {
console.log(val);
this.$bus.emit("getMsg", val)
}
}
};
</script>
<style lang="scss" scoped>
</style>
<template>
<div>
我是平行组件2
{{msg1}}
</div>
</template>
<script>
export default {
data() {
return {
msg1: '',
};
},
created() {
this.$bus.on('getMsg', this.getBus);
},
methods: {
getBus(val) {
console.log("这个是中央事件总线得到的值", val)
this.msg1 = val;
}
},
beforeDestroy() {
this.$bus.off('getMsg', this.getBus);
}
};
</script>
<style lang="scss" scoped>
</style>
- 然后将
child1 和 child2 两个组件导入使用,点击触发对应的事件,即可看到平行组件间的传值。
参考链接:cloud.tencent.com/developer/a…