插件方式:
npm install vue-bus --save
// main.js
import Vue from 'vue';
import VueBus from 'vue-bus';
Vue.use(VueBus);
// A 组件
<template>
<div class="wrap">
<button @click="sendMsg">触发</button>
</div>
</template>
<script>
export default {
data(){
return {
Amsg:'我是来自A组件的信息',
}
},
methods:{
sendMsg(){
this.$bus.emit('changeMsg', this.Amsg );
this.$bus.emit('doOnce','我只会触发一次');
}
},
}
</script>
// B 组件
<template>
<div>
<h3>{{Bmsg}}</h3>
</div>
</template>
<script>
export default {
data(){
return {
Bmsg:'我是B组件',
}
},
methods:{
getMsg(msg){
this.Bmsg = msg;
console.log(msg);
}
},
created(){
/*
* 接收事件
* 这种写法也体现了:A 组件调用 B 组件中的方法。如果只是传递数据,可参考如下简化写法:
* this.$bus.on('changeMsg', (msg) => { this.Bmsg = msg });
*/
this.$bus.on('changeMsg', this.getMsg);
// 此侦听器只会触发一次
this.$bus.once('doOnce', (txt) => { console.log(txt) });
},
// 组件销毁时,移除EventBus事件监听
beforeDestroy() {
this.$bus.off('changeMsg', this.getMsg);
},
}
</script>
不用插件方式:
//main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
Vue.prototype.bus = new Vue() //此处全局注册一个Vue作为事件中心
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
}
<template>
<div class="hello" style="border:1px solid #666">
<h1>Brother1 component</h1>
<h2 @click="send">click send onb2</h2>
</div>
</template>
<script>
export default {
name: 'Brother1',
data () {
return {
msg: 'Brother1'
}
},
methods: {
send () {
this.bus.$emit('onb2', 'from brother1') // 触发Brother2.vue监听的onb2事件
}
},
created () {
this.bus.$on('onb1', (param) => { // 创建时,进行事件onb1监听
console.log('receive onb1', param)
})
},
beforeDestroy () {
this.bus.$off('onb1') // 销毁时,事件onb1监听取消
console.log('onb1 listener was closed')
}
}
</script>
<template>
<div class="hello" style="border:1px solid #666">
<h1>Brother2 component</h1>
<h2 @click="send">click send onb1</h2>
</div>
</template>
<script>
export default {
name: 'Brother2',
data () {
return {
msg: 'Brother2'
}
},
methods: {
send () {
this.bus.$emit('onb1', 'from brother2') // 触发Brother1.vue监听的onb1事件
}
},
created () {
this.bus.$on('onb2', (param) => { // 创建时,进行事件onb1监听
console.log('receive onb2', param)
})
},
beforeDestroy () {
this.bus.$off('onb2') // 销毁时,事件onb2监听取消
console.log('onb2 listener was closed')
}
}
</script>