<script type="x/template" id="child-template">
<input v-model="msg">
<button v-on:click="notify">Dispatch Event</button>
</script>
<div id="events-example" class="demo">
<p>Messages: {{ messages | json }}</p>
<child v-on:child-msg="handleIt"></child>
</div>
<script>
Vue.component('child', {
template: '#child-template',
data: function () {
return { msg: 'hello' }
},
methods: {
notify: function () {
if (this.msg.trim()) {
this.$dispatch('handleIt', this.msg);
this.msg = ''
}
}
}
})
var parent = new Vue({
el: '#events-example',
data: {
messages: []
},
events: {
'handleIt': function (msg) {
this.messages.push(msg)
}
}
})
</script>
如上代码中,自定义的child-msg事件是如何触发的并最终执行了handleIt函数?
這邊其實並沒有被觸發,因為並沒有名為
child-msg
的事件被dispatch
真正被觸發的是你寫在這邊的
events
如果你是想靠
v-on:child-msg="handleIt"
來處理事件的話,你應該是要把handleIt
放在methods
裡面,然後this.$dispatch('child-msg', this.msg)
才對。這裡我稍稍修改了你的代碼:https://jsfiddle.net/tomoeba/97kmbrye/1/