在 Vue.js 中监听自定义事件 [英] Listen to custom event in Vue.js
问题描述
Vue.js 适用于浏览器事件,例如 click
或 mousedown
.但根本不适用于自定义事件.代码如下:
HTML:
JavaScript:
new Vue({el: '#app',数据: {},方法: {平:功能(事件){console.log('Vue ping', 事件);alert('Vue ping');},点击:功能(事件){jQuery(event.target).trigger('ping');}},准备好:函数(){console.log(this.$els);jQuery(this.$els.ping).on('ping', function (event) {console.log('jQuery ping', 事件);alert('jQuery ping');});}});
我希望 Vue ping
和 jQuery ping
发出警报.但只有后者弹出.
Vue 有自己的内部 用于自定义事件的系统,您应该使用它来代替 jQuery/原生 DOM 事件:
点击:函数(事件){//jQuery(event.target).trigger('ping');this.$dispatch('ping', event.target)//将事件向上发送到父链,可以选择发送对元素的引用.//或者:this.$emit('ping')//在当前实例上触发事件}
$dispatch 用于父子通信,您似乎想从同一个组件内触发自定义事件.在这种情况下,您可以改为简单地调用一个方法.
如果您仍想在同一个组件内监听自定义事件,您可以:
- 想要使用 $emit
不能在模板中使用
v-on:custom-event-name
(只能在组件上使用).而是将事件方法添加到events:
:事件:{平:函数(){....}}
Vue.js works great with browser events such as click
or mousedown
. But not work at all with custom events. Here is the code:
HTML:
<div id="app" style="display: none" v-show="true">
<div v-el:ping v-on:ping="ping">
<div>
<button v-on:click="click">Click</button>
</div>
</div>
</div>
JavaScript:
new Vue({
el: '#app',
data: {
},
methods: {
ping: function (event) {
console.log('Vue ping', event);
alert('Vue ping');
},
click: function (event) {
jQuery(event.target).trigger('ping');
}
},
ready: function () {
console.log(this.$els);
jQuery(this.$els.ping).on('ping', function (event) {
console.log('jQuery ping', event);
alert('jQuery ping');
});
}
});
I expect alert with Vue ping
and jQuery ping
. But only the later pops up.
Vue has it's own internal system for custom events, which you should use instead of jQuery / native DOM events:
click: function (event) {
// jQuery(event.target).trigger('ping');
this.$dispatch('ping', event.target) // send event up the parent chain, optionally send along a reference to the element.
// or:
this.$emit('ping') // trigger event on the current instance
}
Edit: $dispatch is for parent-child communication, You seem to want to trigger a custom event from within the same comonent. In that case, you could instead simply call a method.
If you still want to listen to a custom event inside the same component, you:
- want use $emit
cannnot use
v-on:custom-event-name
in the template (that's only to be used on components). Rather, add the event method to theevents:
:events: { ping: function() {....} }
这篇关于在 Vue.js 中监听自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!