前面介绍了父组件可以通过prop向子组件传递数据,反过来,子功能有些时候需要和父组件进行通信,那该如何实现呢?
父子组件之间传递数据

父子组件之间传递数据
在Vue.js中如果子组件需要给父组件传送数据,需要在子组件中定义一个自定义事件,事件名称不需要加括号。在子组件中通过$emit触发自定义事件,父组件使用v-on来监听事件。将需要传递的参数通过emit的第二个参数传递的。$emit方法的语法是:
vm.$emit(eventName,[...args]) eventName是事件名,args是附加参数,这些参数回会传给监听器的回调函数。如果子事件需要向父组件传递数据,就可以通过第二个参数来传。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id ="app">
{{total}}
<button-counter v-on:increment='increTotal'></button-counter>
<button-counter v-on:increment='increTotal'></button-counter>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("button-counter",{
// 按钮绑定方法incremention
template:"<button v-on:click='incremention'>{{counter}}</button>",
data:function(){
return{
counter : 0
}
},
methods:{
incremention(){
this.counter += 1,
// 通过实例的$emit()方法触发自定义事件increment,并传递参数
this.$emit("increment",this.counter)
}
}
})
new Vue({
el:"#app",
data:{
total:0
},
methods:{
// 自定义事件的附加参数会自动传入方法
increTotal(counter){
this.total+=counter
}
}
})
</script>
</body> 子事件的按钮绑定方法incremention方法,在此方法中通过$emit()方法触发一个自定义的事件increment。并在组件实例中监听这个事件,当事件被触发了时,调用在父组件中的interTotal事件,并将参数调入其中。