vue非父子元件間的傳值 Bus/匯流排機制/釋出訂閱模式/觀察者模式
阿新 • • 發佈:2018-11-07
Bus/匯流排機制/釋出訂閱模式/觀察者模式
我們需要將一個元件的子元件的資料傳遞給另一個元件的子元件
① 將Vue的例項賦值給Vue.prototype.bus,這樣只要我們之後呼叫new Vue()或者建立元件的時候,每一個元件上都會有Bus這個屬性,因為每一個元件或者Vue這個例項都是通過Vue這個類來建立的,而我們在Vue的類上掛了一個Bus的屬性,而且掛在Vue類的prototype上面,所有每一個通過Vue建立的,也就是Vue的例項上都會有Bus這個屬性,它都指向同一個Vue的例項。
②在子元件裡面繫結一個點選事件,如 @click="handleClick",
③在此提交一個自定義事件 如: this.bus.$emit('change',this.selfContent)
④在父元件中使用$on監聽bus上觸發出來事件
var this_ = this; // this作用域發生了變化,所以在這裡做一次儲存
this.bus.$on('change',function(msg){
this_.selfContent = msg;
})
⑤改變父元件接收過來的資料,要做一次備份,才方便修改,因為vue裡面是單向資料流,子元件不能改變父元件,如下:
data: function(){
return {
selfContent: this.content
}
},
<body> <div id="app"> <child content="hello"></child> <child content="world"></child> </div> <script> Vue.prototype.bus = new Vue() Vue.component('child', { props: ['content'], data: function(){ return { selfContent: this.content } }, template: '<div @click="handleClick">{{selfContent}}</div>', methods:{ handleClick: function(){ this.bus.$emit('change',this.selfContent) } }, mounted: function(){ var this_ = this; this.bus.$on('change',function(msg){ this_.selfContent = msg; }) } }) var vm = new Vue({ el: "#app" }) </script> </body>