<script type="x/template" id="child-template">
<input v-model="msg">
<button v-on:click="notify">Dispatch Event</button>
</script>
<p id="events-example" class="demo">
<p>Messages: {{ messages | json }}</p>
<child v-on:child-msg="handleIt"></child>
</p>
<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函数?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
這邊其實並沒有被觸發,因為並沒有名為
child-msg的事件被dispatch真正被觸發的是你寫在這邊的
events如果你是想靠
v-on:child-msg="handleIt"來處理事件的話,你應該是要把handleIt放在methods裡面,然後this.$dispatch('child-msg', this.msg)才對。這裡我稍稍修改了你的代碼:https://jsfiddle.net/tomoeba/97kmbrye/1/
我觉得代码是不是有点问题?没看到哪里触发
child-msg事件啊?当你点击
button的时候执行了button的click事件,然后执行了notify方法,然后在notify方法里面dispatch了你自定义的handleIt事件,也就是说是依赖button的click事件可以参考下这里:http://cn.vuejs.org/api/#vm-dispatch