javascript this.$root.$emit 在 Vue 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50181858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:58:04  来源:igfitidea点击:

this.$root.$emit not working in Vue

javascriptvuejs2

提问by Mattias

I want to emit an event on the root component, and listen to in in the root component. In a child of child component I do this:

我想在根组件上发出一个事件,并在根组件中监听。在子组件的子组件中,我这样做:

this.$root.$emit('access-token', accessToken);

In root component (the top component, first to load) I do this (edit: this is in the mounted() method):

在根组件(顶部组件,首先加载)中,我这样做(编辑:这是在 mount() 方法中):

this.$on('access-token', this.setAccessToken);

It doesn't react to the event though. Why?

但它不会对事件做出反应。为什么?

回答by Andres Garcia

You are not using the $rootfor the event $on

您没有$root在活动中使用$on

Change this:

改变这个:

this.$on('access-token', this.setAccessToken); 

for this:

为了这:

this.$root.$on('access-token', this.setAccessToken);