从父组件向子组件传递数据使用props方法,Vue通信有大体上以下几种方式:
组件关系可以分为:父子组件通信,兄弟组件通信、跨级组件通信。
一、自定义事件
当子组件需要向父组件传递数据时,就需要用到自定义事件。
子组件用$emit()来出发事件,父组件用$on()来监听子组件的事件。
父组件也可以在子组件自定义的标签上使用v-on来监听子组件触发的自定义事件。示例如下:
<div id='app'>
<p>{{total}}</p>
<my-component @increase='handleGetTotal' @reduce='handleGetTotal'></my-component>
</div>
<script>
Vue.component('my-component',{
template:'\
<div>\
<button @click='handleIncrease'>+1</button>\
<button @click='handleReduce'>-1</button>\
</div>'
data:function(){
return {
counter:0
}
},
methods:{
handleIncrease(){
this.counter++;
this.$emit('increase',this.counter);
},
handleReduce(){
this.counter++;
this.$emit('reduce',this.counter);
},
}
})
var app=new Vue({
el:'#app',
data:{
total:0,
}
methods:{
handleGetTotal:function(count){
this.total=count;
}
}
})
</script>
上面的示例中,有两个按钮,分别实现加1和减1的功能,通过改变按钮的counter的值,然后通过$emit()将数据传入到父组件中中,父组件使用v-on进行接收,$emit的第一个参数,就是父组件自定义事件的名称,后面的参数就是要传递的数据,可以不填或者填写多个。
未完待续......