组件之间传参的一种方式,可以实现人已组建之间的数据通信
如:A组件想给C组件传参,那么A事件需要触发事件B并携带参数
首先需要在主入口文件mind.js中定义事件总线
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
// 定义事件总线
beforeCreate(){
Vue.prototype.$bus=this
}
}).$mount('#app')
C组件中注册一个事件总线
<template>
<div> </div>
</template>
<script>
export default {
name:'TestC',
mounted(){
// 在总线上注册一个事件
this.$bus.$on("B",function(data){
console.log("B事件触发,接收到",data)
})
},
// 组件销毁后取消事件
beforeDestory(){
console.log('组件已销毁')
this.$bus.$off("B")
}
}
</script>
A组件中定义点击事件,点击的同时触发事件总线上的事件B并传值
<template>
<div>
<button @click='emitEvent'>点击触发事件总线B事件</button>
</div>
</template>
<script>
export default {
name:'TestA',
methods:{
emitEvent(){
// 触发总线上的B事件
this.$bus.$emit("B",100)
}
}
}
</script>
将A组件和C组件引入到App.vue中打开,
点击按钮后触发事件,事件在控制台中展示