Vue.js 如何创建用于全局事件处理的Vue总线?
我正在节点/网页包/Vue路由器环境中使用Vue,并尝试设置全局事件处理程序或总线。但它不起作用。它显示为未定义。以下是我的设置: main.js:Vue.js 如何创建用于全局事件处理的Vue总线?,vue.js,event-handling,vue-router,event-bus,Vue.js,Event Handling,Vue Router,Event Bus,我正在节点/网页包/Vue路由器环境中使用Vue,并尝试设置全局事件处理程序或总线。但它不起作用。它显示为未定义。以下是我的设置: main.js: //Declare event handler Object.defineProperty(Vue.prototype, '$bus', { get () { return this.$root.bus } }) //Declare app instance new Vue({ el: '#app', router,
//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/>'
})
但这也不起作用。这是使用箭头功能的问题。虽然
()=>{}
语法看起来比函数(){}
更好,但有一点不同,那就是箭头函数使用了这个
的词法上下文(从定义它的地方,而不是从调用它的地方,这个实例中您需要的id),这意味着this
不再是Vue实例,因此您不能使用this.$bus
。您可以通过使用created:function(){…
或简明(但功能等效)版本created(){…
通过查找有关es6、箭头函数、词法范围、此上下文的文章,您可以了解更多有关差异的信息
main.js代码:
import Vue from "vue";
import App from "./App";
Vue.prototype.$bus = new Vue();
new Vue({
el: "#app",
components: { App },
template: "<App/>"
});
哦!没错,这就是问题所在。谢谢你的帮助。“箭头函数创建了自己的上下文”我相信你不是有意这样说的。它与声明它的位置共享相同的this
上下文。而函数
从调用它的位置获取this
。是的,谢谢你指出这一点。我还认为MSDN中的引用有误导性。我发现,仅此解释并不能清楚地说明为什么不能他宣称上下文不起作用。
//Declare event handler
const eventBus = new Vue()
Vue.prototype.$bus = eventBus
import Vue from "vue";
import App from "./App";
Vue.prototype.$bus = new Vue();
new Vue({
el: "#app",
components: { App },
template: "<App/>"
});
export default {
name: "App",
created() {
console.log(this.$bus);
}
};