兄弟組件之間互相傳值,需要建立一個“中轉站”(新的vue實例),并且需要主動觸發(fā)。
實例上的$on方法來接受監(jiān)聽。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>組件傳值</title> <script src="vue.js"></script></head><body> <div id="box"> <child1></child1> <child2></child2> </div> <template id="c1"> <h1>~~~~~~我是哥哥~~~~{{msg}} <button @click='fn'>點擊</button></h1> </template> <template id="c2"> <h3>~~~~~~我是弟弟~~~~{{msg2}}</h3> </template></body></html><script> var Hub=new Vue(); // 1) 中轉站,其中不需要設置任何參數 var vm=new Vue({ el: '#box', components:{ child1:{ template:'#c1', data:function(){ return { msg: 'hello' } }, methods:{ fn:function(){ // 2) 主動觸發(fā)監(jiān)聽(中轉站觸發(fā)監(jiān)聽) console.log(this.msg); //hello Hub.$emit('change',this.msg) //$emit觸發(fā)監(jiān)聽方法 } } }, child2:{ template:'#c2', data:function(){ return { msg2: 'world' } }, // 創(chuàng)建完成 new Vue create mount // 鉤子函數 created(){ // 3) 接收監(jiān)聽 $on('事件名稱',function(val){}) val是傳遞過來的值 Hub.$on('change',function(val){ console.log(val) //hello // this.msg2 = val; }) } } } })</script>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答