需要注意的是使用事件总线对象需要先在main.js中全局事件总线$bus配置,在任何地方都可以使用。
main.js
import Vue from 'vue'
import App from './App.vue'
//引入路由
import router from '@/router'
//引入仓库
import store from '@/store';
new Vue({
render: h => h(App),
//配置全局事件总线$bus
beforeCreate(){
Vue.prototype.$bus=this;
},
//注册路由信息
router,
//注册仓库
store,
}).$mount('#app')
示例 子组件1中点击事件触发,向子组件2中传值。
子组件1
<template>
<div>
<h1>子组件1</h1>
<button @click="go" >数据派发</button>
</div>
</template>
<script>
export default {
methods: {
go() {
//使用事件总线对象派发 data 事件
this.$bus.$emit('data','我携带了参数')
},
}
}
</script>
子组件2
<template>
<div>
<h1>子组件2</h1>
</div>
</template>
<script>
export default {
mounted() {
//组件挂载完毕后,通过全局总线绑定data事件监听
this.$bus.$on('data',res=>{
alert(res)
//此处也可以写自己的业务逻辑
})
}
}
</script>