非父子組件間的傳值
通過在Vue.prototype上綁定bus屬性,在之後所創建的vue實例都具有bus這個屬性,子屬性接收到數據後,通過emit向父組件傳值,通過每個組件都含有的生命週期鉤子mounted,創建方法通過this.bus.$on觸發傳值的事件並接收所傳的值
<div id="app">
<child content="Box"></child>
<child content="Min"></child>
</div>
<script>
//在生成vue實例前,給Vue的原型上添加一個bus屬性,這個屬性是vue的實例,
//之後創建的vue實例都具有bus這個屬性
Vue.prototype.bus = new Vue()
Vue.component('child',{
data: function(){
return {
selfContent: this.content
}
},
props:['content'],
template: '<div @click="hdclick">{{selfContent}}</div>',
methods:{
hdclick: function() {
//向父組件傳值,觸發事件change
this.bus.$emit('change',this.selfContent)
}
},
mounted: function() {
//因爲this的指向發生了變化,不用箭頭函數的話就要先把this保存起來
var this_ = this
//監聽事件change
this.bus.$on('change',function(msg){
this_.selfContent = msg
})
}
})
var app = new Vue({
el:"#app",
})