javascript - VueJs v-on :event and this. $on(event, handler) 有什么区别?

标签 javascript vue.js vue-events

我正在学习 Vuejs 事件处理
我认为开发人员可以使用 this.$on('event', handler)js 文件中处理 'event'

有一个example .

<div id="mainapp" v-on:event="processEventFromView">
    <button type="button" v-on:click="emitEvent">
       Emit Event
    </button>
</div>

js文件

var app = new Vue({
  el:"#mainapp",
  data:{
    show:false
  },
  created:function(){
     this.$on('event', this.processEvent);
  },
  methods:{
      emitEvent:function(){
          this.$emit('event', {data:'mydata'});
      },
      processEvent(data){
         console.log('js', data);  //this is fired when clicking the button.
      },
      processEventFromView(data){
         console.log('view', data);  //this is not fired whenever.
      }      

   }
})

但在示例中,只有处理程序 processEventthis.$on() 附加,在单击按钮时被触发。 v-onthis.$on 有什么区别?
为什么 v-on:event="processEventFromView" 不被调用?
我可以将 事件处理程序 附加到按钮的 click 事件并引用 ref , 而不是 v-on:click="emitEvent"?
请帮我看看我哪里错了。

最佳答案

我想这与 Vue 的 Linus Berg 在这里相关并回答了 https://stackoverflow.com/a/36159698/1225266 虽然它与早期版本的 Vue 有关(该帖子来自 2016 年),但我想它仍然适用。

简单回答你的问题

Why is v-on:event="processEventFromView" not called whenever?

是(我引用)

cannnot use v-on:custom-event-name in the template (that's only to be used on components).

关于javascript - VueJs v-on :event and this. $on(event, handler) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000720/

相关文章:

javascript - 如何使用reactjs/javascript在单个Excel工作表中导出2个表

javascript - Uncaught ReferenceError : $ is not defined error in jQuery

javascript - localstorage javascript 中的效果更改

vue.js - 如何使用 Vuetify 在 Combobox 组件中使用掩码?

vue.js - v-on :change does not work for vue-multiselect

javascript - 如何在 $(document).ready(function(){}) 中使用 for 循环?

javascript - 数组最大长度不起作用

javascript - vue-async-data 不工作

vue.js - 有条件地将 @submit.prevent 添加到 Vue.js 中的表单