在 Vue.js 中监听自定义事件 [英] Listen to custom event in Vue.js

查看:85
本文介绍了在 Vue.js 中监听自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vue.js 适用于浏览器事件,例如 clickmousedown.但根本不适用于自定义事件.代码如下:

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 pingjQuery ping 发出警报.但只有后者弹出.

代码笔

解决方案

Vue 有自己的内部 用于自定义事件的系统,您应该使用它来代替 jQuery/原生 DOM 事件:

点击:函数(事件){//jQuery(event.target).trigger('ping');this.$dispatch('ping', event.target)//将事件向上发送到父链,可以选择发送对元素的引用.//或者:this.$emit('ping')//在当前实例上触发事件}

$dispatch 用于父子通信,您似乎想从同一个组件内触发自定义事件.在这种情况下,您可以改为简单地调用一个方法.

如果您仍想在同一个组件内监听自定义事件,您可以:

  1. 想要使用 $emit
  2. 不能在模板中使用 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.

CodePen

解决方案

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:

  1. want use $emit
  2. cannnot use v-on:custom-event-name in the template (that's only to be used on components). Rather, add the event method to the events::

    events: { ping: function() {....} }

这篇关于在 Vue.js 中监听自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆