p>我们知道,父组件使用 prop 传递数据给子组件。但子组件怎么跟父组件通信呢?这个时候 Vue 的自定义事件系统就派得上用场了。
每个 Vue 实例都实现了事件接口,即:
使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件
父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
<div id="app">
<p>{{ total }}</p>
<counter v-on:add="addTotal"></counter>
<counter v-on:add="iaddTotal"></counter>
</div>
Vue.component('counter', {
template: '<button v-on:click="addCounter">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
addCounter: function () {
this.counter += 1
this.$emit('add')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
addTotal: function () {
this.total += 1
}
}
})