核心思想:使用一个新的vue实例及其$on和$emit方法触发事件
第一步,给vue原型增加一个新的vue对象
Vue.prototype.$eventBus = new Vue()
第二步:在需要向外传递时使用$emit
<template>
<div class="son">
<h1>这是son组件</h1>
<button @click="vueBus">使用$bus进行通信</button>
</div>
</template>
<script>
export default {
name: "Son",
data(){
return {
sonData:1
}
},
methods: {
vueBus(){
this.$eventBus('bus',this.sonData)
}
}
}
</script>
<style scoped>
.son {
background-color: darkgray;
color: white;
}
</style>
第三步:在监听需要这个事件的组件的mounted函数内,使用$on监听事件
<template>
<div class="son">
<h1>这是son2组件</h1>
</div>
</template>
<script>
export default {
name: "Son",
mounted(){
this.$eventBus.$on('bus',value=>console.log(value))
},
}
</script>
<style scoped>
.son {
background-color: darkgray;
color: white;
}
</style>
注意:如果某些事件挂载时就触发需要注意vue生命周期(父created-子created-子mounted-父mounted)。如果需要在子组件mounted时emit事件,并且触发父组件里的on,此时是无法实现的,因为父组件还没有执行$on,就需要子组件中使用$nextTick,在$nextTick中触发emit