首先需要在任意地方添加一個bus.js;
在bus.js里面 寫入下面信息
import Vue from 'vue' export default new Vue;
在需要通信的組件都引入Bus.js
如果你的bus.js是自定義一個bus的文件那from后面就改成你的所放的位置
import Bus from './bus.js'
接下來就是要組件通信了
添加一個 觸發 #emit的事件按鈕
<template>
<div id="emit">
<button @click="bus">按鈕</button>
</div>
</template>
import Bus from './bus.js'
export default {
data() {
return {
message: ''"
}
},
methods: {
bus () {
Bus.$emit('msg', '我要傳給兄弟組件們,你收到沒有')
}
}
}
打開要和$emit通信的另外一個組件
在鈎子函數中監聽msg事件
<template>
<div id="on">
<p>{{message}}</p>
</div>
</template>
import Bus from './bus.js'
export default {
data() {
return {
href: 'www.dddddd//d/d/d'
}
},
mounted() {
$("body").on("click",".router_itme",function(){
//發送方
Bus.$emit("hrefs", this.href);
})
}
}
打開要和$emit通信的另外一個組件 ,在鈎子函數中監聽msg事件
<template>
<div id="on">
<p>{{message}}</p>
</div>
</template>
import Bus from './bus.js'
export default {
data() {
return {
href : ''
}
},
mounted(){
// this.href = location.href.split('#')[1]
// 接收傳header組件傳過來的路徑
let self = this;
Bus.$on('hrefs', (e) => {
self.href = e.split('#')[1]
})
}
}
