如何为全局事件处理创建Vue总线?

时间:2018-05-17 15:49:02

标签: vue.js event-handling vue-router event-bus

我在Node / Webpack / Vue Router环境中使用Vue并尝试设置全局事件处理程序或总线。但它不起作用。它显示为未定义。这是我的设置:

main.js:

//Declare event handler
Object.defineProperty(Vue.prototype, '$bus', {
  get () {
    return this.$root.bus
  }
})

//Declare app instance
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

App.vue

<script>
export default {
  name: 'App'
  created: () => {
    console.log(this.$bus);
  }
}
</script>

console.log语句返回undefined,这意味着事件处理程序无法以某种方式传递给应用程序。我还尝试了以下语句来声明事件处理程序:

main.js

//Declare event handler
const eventBus = new Vue()
Vue.prototype.$bus = eventBus

但这也不起作用。

1 个答案:

答案 0 :(得分:1)

这是使用箭头功能的问题。虽然() => {}语法看起来比function() {}好,但是有一点不同,因为箭头函数使用this的词汇上下文(从定义它的位置,而不是从它的位置)被调用,在这个实例中你需要的是id),这意味着this不再是Vue实例,所以你不能使用this.$bus。您可以使用created: function() {...或简洁(但功能相同)版本created() {...

将箭头函数替换为常规函数来解决此问题。

您可以在es6, arrow functions, lexical scope, this context上查找文章,了解有关差异的更多信息。

main.js代码:

import Vue from "vue";
import App from "./App";

Vue.prototype.$bus = new Vue();

new Vue({
  el: "#app",
  components: { App },
  template: "<App/>"
});

app.js中的某个地方

export default {
  name: "App",
  created() {
    console.log(this.$bus);
  }
};
相关问题