在Vue.js中收听自定义事件

vba*_*osh 8 javascript vue.js

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

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.但只有后来弹出.

CodePen

Lin*_*org 9

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用于父子通信,您似乎想要从同一个组件中触发自定义事件.在这种情况下,您可以简单地调用方法.

如果您仍想在同一组件中收听自定义事件,则:

  1. 想要使用$ emit
  2. 不能v-on:custom-event-name在模板中使用(仅用于组件).而是将事件方法添加到events::

    事件:{ping:function(){....}}


Jef*_*eff 2

这是普通 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