结合菜鸟教程-vue组件的一个例子来说明一下自定义事件的运行流程
<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
</script>
<button-counter></button-counter>
是个子组件- 它监听到鼠标点击事件时会触发子组件定义中的
incrementHandler
事件 - 而这个
incrementHandler
事件会通过this.$emit('increment')
触发increment事件,于是在父组件的定义中,就可以触发incrementTotal
事件来对父组件中的total值进行修改了