使用v-on
綁定自定義事件可以讓子組件向父組件傳遞數據,用到了this.$emit
(‘自定義的事件名稱',傳遞給父組件的數據)
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="../js/vue.js"></script></head><body><div id="app"><parent-component></parent-component></div><template id="parent-component"><div> <p>總數是{{total}}</p> <child-component @increment="incrementTotal"></child-component> <!--@increment是子組件this.$emit('increment'自定義的事件用來告訴父組件自己干了什么事 然后會觸發父子間incrementTotal的方法來更新父組件的內容)--></div></template><template id="child-component"> <button @click="increment()">{{mycounter}}</button></template><script> var child=Vue.extend({ template:"#child-component", data:function () { return { mycounter:0 } }, methods:{ increment:function(){ this.mycounter=10; this.$emit("increment",this.mycounter);//把this.mycounter傳遞給父組件 } } }) var parent=Vue.extend({ data:function () { return { total:0 } }, methods:{ incrementTotal:function(newValue){ this.total+=newValue; } }, template:"#parent-component", components:{ 'child-component':child } }) var vm=new Vue({ el:"#app", components:{ 'parent-component':parent } })</script></body></html>
@increment是子組件this.$emit('increment'自定義的事件,newValue)用來告訴父組件自己干了什么事
同時還可以傳遞新的數據給父組件
然后會觸發父子間incrementTotal的方法來更新父組件的內容)。
這里需要注意幾個點:
1.
圖中紅色圈中的部分是對應的,子組件在自己的methods方法里面寫自己的事件實現,然后再父組件里面寫字組件時給子組件綁定上methods方法里面的
事件名稱,要一一對應
這里自定義事件里面的要寫父組件的方法名,父組件里面定義該方法。
父組件里面的方法可以接收子組件this.$emit('increment',this.mycounter);
傳遞過來的數值:this.mycounter
,
到父組件的方法里面就是newValue參數,這樣就實現了子組件向父組件傳遞數據
以上所述是小編給大家介紹的vue子組件使用自定義事件向父組件傳遞數據,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答