Vue.js适用于浏览器事件,如click或mousedown.但是根本不适用于自定义事件.这是代码:
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>
Run Code Online (Sandbox Code Playgroud)
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');
});
}
});
Run Code Online (Sandbox Code Playgroud)
我希望Vue ping和他一起警惕jQuery ping.但只有后来弹出.
Vue拥有自己的自定义事件内部系统,您应该使用它而不是jQuery/native DOM事件:
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
}
Run Code Online (Sandbox Code Playgroud)
编辑:$ dispatch用于父子通信,您似乎想要从同一个组件中触发自定义事件.在这种情况下,您可以简单地调用方法.
如果您仍想在同一组件中收听自定义事件,则:
不能v-on:custom-event-name在模板中使用(仅用于组件).而是将事件方法添加到events::
事件:{ping:function(){....}}
这是普通 JS 中的:
HTML:
<div id="app">
<div v-el:ping>
<div>
<button v-on:click="click">Click</button>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
(function() {
new Vue({
el: '#app',
data: {
event: null
},
methods: {
ping: function(event) {
alert('Vue ping');
},
click: function(event) {
this.$els.ping.dispatchEvent(this.event);
}
},
ready: function() {
this.event = document.createEvent("HTMLEvents");
this.event.initEvent("ping", true, true);
this.$els.ping.addEventListener('ping', this.ping);
}
});
})();
Run Code Online (Sandbox Code Playgroud)
笔: http: //codepen.io/anon/pen/wGdvaV? editors=1010#0
| 归档时间: |
|
| 查看次数: |
21969 次 |
| 最近记录: |