这个.$ root.$ emit在Vue中不起作用

Mat*_*ias 11 javascript vuejs2

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

this.$root.$emit('access-token', accessToken);
Run Code Online (Sandbox Code Playgroud)

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

this.$on('access-token', this.setAccessToken);
Run Code Online (Sandbox Code Playgroud)

但它并没有对事件作出反应.为什么?

小智 26

您没有使用$root该活动$on

改变这个:

this.$on('access-token', this.setAccessToken); 
Run Code Online (Sandbox Code Playgroud)

为了这:

this.$root.$on('access-token', this.setAccessToken);
Run Code Online (Sandbox Code Playgroud)

  • 似乎值得一提的是,vue 似乎并不鼓励这种方法,并建议使用虚拟组件作为事件总线或 vuex-https://vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced (2认同)