<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.app {
display: flex;
}
.app div {
flex: 1;
}
</style>
</head>
<body>
<div id='app' class='app'>
<div>
<child-a></child-a>
</div>
<div>
<child-b></child-b>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 事件總線(xiàn),通過(guò)“訂閱-發(fā)布”模式實(shí)現(xiàn)組件之間的直接通信
1.首先創(chuàng)建一個(gè)空的vue實(shí)例
var bus = new Vue()
它身上有兩個(gè)方法實(shí)現(xiàn)組件之間的通信纤怒,bus.$emit(頻道档泽,數(shù)據(jù))定義 在組件的methods中悦析,用來(lái)向其他組件發(fā)送消息乓搬,bus.$on(頻道,數(shù)據(jù))用來(lái)接收其他組件發(fā)來(lái)的消息幔欧,定義在生命周期的created或者mounted鉤子函數(shù)中。
// bus.$emit('頻道') 發(fā)送消息
// bus.$on('頻道') 收到消息
當(dāng)兩個(gè)組件發(fā)送數(shù)據(jù)的頻道和接收消息的頻道相同就可以實(shí)現(xiàn)組件之間的雙向通信了
Vue.component('child-a', {
data: function() {
return {
msg: '',
html: ''
}
},
template:`
<div>
<input type="text" v-model='msg' @keyup.enter='send'>
<button @click='send'>發(fā)送</button>
//給輸入框和button按鈕都綁定send事件干厚,當(dāng)監(jiān)聽(tīng)到鍵盤(pán)enter事件或按鈕點(diǎn)擊事件李滴,執(zhí)行事件函數(shù)send
<div v-html='html'></div>
</div>
`,
methods: {
send() {
// 發(fā)送消息
bus.$emit('A', this.msg)
子組件a廣播了一件非定向消息,消息內(nèi)容為msg,msg就是輸入框中的內(nèi)容蛮瞄。廣播頻道為A所坯,
子組件b要接收這條消息,就要監(jiān)聽(tīng)廣播頻道A
this.msg = ''
}
},
created() {
var that = this
普通函數(shù)會(huì)改變this指向
bus.$on('B', function(msg) {
子組件a監(jiān)聽(tīng)頻道B的消息挂捅,并執(zhí)行回調(diào)函數(shù)芹助,將消息內(nèi)容渲染到div中
that.html += '<div>B說(shuō):'+msg+'</div>'
that指向組件實(shí)例,可以調(diào)用組件上的屬性和方法
})
}
})
Vue.component('child-b', {
data: function() {
return {
msg: '',
html: ''
}
},
template:`
<div>
<input type="text" v-model='msg' @keyup.enter='send'>
<button @click='send'>發(fā)送</button>
<div v-html='html'></div>
</div>
`,
methods: {
send() {
bus.$emit('B', this.msg)
this.msg = ''
}
},
created() {
var that = this
bus.$on('A', function(msg) {
//監(jiān)聽(tīng)的頻道,收到消息后的回調(diào)函數(shù)
that.html += '<div>A說(shuō):'+msg+'</div>'
})
}
})
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>
效果實(shí)例
HTML結(jié)構(gòu)