1.把Vue.prototype上掛載一個bus屬性,這個屬性指向1個vue實例,
以后創建組件的時候,每個組件上都會有bus這個屬性,都指向同一個實例
Vue.prototype.bus = new Vue();
2.發布
在methods里使用 this.bus.$emit 發布廣播
methods:{ broadcast: function() { this.bus.$emit('change', this.selfContent);//發布change事件並且攜帶參數 }
3.訂閱
在mounted里使用this.bus.$on 訂閱事件
mounted: function () { var _this = this; this.bus.$on('change', function (msg) { //訂閱change事件 _this.selfContent = msg; } )
全部代碼:
<!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> </head> <body> <div id="app"> <child :content="'全部變成第1項內容'"></child> <child :content="'全部變成第2項內容'"></child> </div> </body> <script type="text/javascript" src="./vue.js"></script> <script <!-- 把Vue.prototype上掛載一個bus屬性,這個屬性指向1個vue實例, 以后創建組件的時候,每個組件上都會有bus這個屬性,都指向同一個實例 --> Vue.prototype.bus=new Vue(); Vue.component('child',{ props:['content'], template:"<div @click='handleClick'>{{selfContent}}</div>", data:function(){ return { selfContent:this.content } }, methods:{ handleClick:function(){ //本組件向外觸發change,並攜帶值 this.bus.$emit('change',this.content); } }, mounted:function(){ var this_=this //其它組件監聽change,並取得值 //兩個child的組件都對change進行了監聽 this.bus.$on('change',function(msg){ console.log('change'); this_.selfContent=msg; }) } }) var app=new Vue({ el:'#app', }) </script> </html>