非父子組件間的傳值
阿新 • • 發佈:2018-11-20
.proto head 觸發事件 觀察者模式 進行 定義 one 鉤子函數 msg
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>非父子組件間的傳值(Bus/總線/發布訂閱模式/觀察者模式)</title> <script src="./vue.js"></script> </head> <body> <div id="root"> <child content="alex"></child> <child content="xu"></child> </div> <script> Vue.prototype.bus= new Vue(); //把綁定總線 Vue.component(‘child‘, { data: function () { return { selfContent: this.content } }, props: { content: String, }, 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 }) //監聽事件,用到鉤子函數mounted } });var vm = new Vue({ el: ‘#root‘ }) </script> </body> </html> <!-- 非父子組件間傳值: 1.Vuex 2.總線機制/Bus/發布訂閱模式/觀察者模式: 在Vue的prototype上定義bus屬性 Vue.prototype.bus = new Vue(); 在組件的methods定義的方法裏使用 this.bus.$emit(‘事件名‘, value); 觸發事件並傳值。 在組件的mounted生命周期鉤子裏使用this.bus.$on(‘事件名‘, function(value){});來監聽所定義的bus屬性上對應的事件被觸發,然後在回調函數裏進行操作。 -->
非父子組件間的傳值