vue子組件使用自定義事件向父組件傳遞數據


使用v-on綁定自定義事件可以讓子組件向父組件傳遞數據,用到了this.$emit(‘自定義的事件名稱’,傳遞給父組件的數據)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script src="../js/vue.js"></script>
 7 </head>
 8 <body>
 9 <div id="app">
10 <parent-component></parent-component>
11 </div>
12 <template id="parent-component">
13 <div>
14     <p>總數是{{total}}</p>
15     <child-component @increment="incrementTotal"></child-component>
16     <!--@increment是子組件this.$emit('increment'自定義的事件用來告訴父組件自己干了什么事
17     然后會觸發父子間incrementTotal的方法來更新父組件的內容)-->
18 </div>
19 </template>
20 <template id="child-component">
21     <button @click="increment()">{{mycounter}}</button>
22 </template>
23 <script>
24     var child=Vue.extend({
25         template:"#child-component",
26        data:function () {
27            return {
28                mycounter:0
29            }
30        },
31         methods:{
32             increment:function(){
33                 this.mycounter=10;
34                 this.$emit("increment",this.mycounter);//把this.mycounter傳遞給父組件
35             }
36         }
37     })
38     var parent=Vue.extend({
39         data:function () {
40             return {
41                total:0
42             }
43         },
44         methods:{
45             incrementTotal:function(newValue){
46                 this.total+=newValue;
47             }
48         },
49         template:"#parent-component",
50         components:{
51             'child-component':child
52         }
53 
54     })
55     var vm=new Vue({
56         el:"#app",
57         components:{
58             'parent-component':parent
59         }
60 
61     })
62 </script>
63 </body>
64 </html>
View Code
@increment是子組件this.$emit('increment'自定義的事件,newValue)用來告訴父組件自己干了什么事
同時還可以傳遞新的數據給父組件
然后會觸發父子間incrementTotal的方法來更新父組件的內容)。
這里需要注意幾個點:
1.

圖中紅色圈中的部分是對應的,子組件在自己的methods方法里面寫自己的事件實現,然后再父組件里面寫字組件時給子組件綁定上methods方法里面的

事件名稱,要一一對應

這里自定義事件里面的要寫父組件的方法名,父組件里面定義該方法。

父組件里面的方法可以接收子組件this.$emit('increment',this.mycounter);傳遞過來的數值:this.mycounter,

到父組件的方法里面就是newValue參數,這樣就實現了子組件向父組件傳遞數據

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM