<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
v-on:child-msg="handleIt"
真正被觸發的是你寫在這邊的 events
events: {
'handleIt': function (msg) {
this.messages.push(msg)
}
}
如果你是想靠 v-on:child-msg="handleIt"
來處理事件的話,你應該是要把 handleIt
放在 methods
裡面,然後 this.$dispatch('child-msg', this.msg)
才對。
這裡我稍稍修改了你的代碼:https://jsfiddle.net/tomoeba/97kmbrye/1/
当你点击button
的时候执行了button
的click
事件,然后执行了notify
方法,然后在notify
方法里面dispatch
了你自定义的handleIt
事件,也就是说是依赖button
的click
事件
可以参考下这里:http://cn.vuejs.org/api/#vm-dispatch
我觉得代码是不是有点问题?没看到哪里触发child-msg
事件啊?
Vue.component('child', {
template: '#child-template',
data: function () {
return { msg: 'hello' }
},
methods: {
notify: function () {
if (this.msg.trim()) {
this.$dispatch('child-msg', this.msg);//这里应该改成child-msg吧,否则代码就真的理解不了了
this.msg = ''
}
}
}
})