核心思想:使用一個新的vue實例及其$on和$emit方法觸發(fā)事件
第一步,給vue原型增加一個新的vue對象
Vue.prototype.$eventBus = new Vue()
第二步:在需要向外傳遞時使用$emit
<template>
<div class="son">
<h1>這是son組件</h1>
<button @click="vueBus">使用$bus進(jìn)行通信</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>
第三步:在監(jiān)聽需要這個事件的組件的mounted函數(shù)內(nèi),使用$on監(jiān)聽事件
<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>
注意:如果某些事件掛載時就觸發(fā)需要注意vue生命周期(父created-子created-子mounted-父mounted)。如果需要在子組件mounted時emit事件,并且觸發(fā)父組件里的on,此時是無法實現(xiàn)的,因為父組件還沒有執(zhí)行$on,就需要子組件中使用$nextTick,在$nextTick中觸發(fā)emit