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参数,这样就实现了子组件向父组件传递数据

 


posted @ 2017-05-27 15:00  fantasy-zxf  阅读(6147)  评论(0编辑  收藏  举报