【问题标题】:EventBus.$on doesn't seem to catch the event being emitted. (Vue js)EventBus.$on 似乎没有捕捉到正在发出的事件。 (Vue.js)
【发布时间】:2020-12-26 02:07:36
【问题描述】:

目前正在尝试从 router.beforeEach 发出一个事件并尝试在我的其他组件中监听它。 然而,虽然 vue devtool 显示事件实际上正在发出,但我的组件似乎无法捕捉到它。 提前谢谢你。

我的 EventBus 声明:

import Vue from 'vue'
export const EventBus = new Vue()

触发事件:

router.beforeEach((to, from, next) => {
            console.log('from',from.name,'to',to.name)
            window.axios.get(checkTokenUrl, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('JWT')}`
                }
            }).then(res => res.data)
                .then(data => {
                    next()
                    if(data === true) {
                        console.log('User is Logged in')
                        EventBus.$emit('Logged-in')
                    }else {
                        console.log('User is Logged out')
                        EventBus.$emit('Logged-Out')
                    }
                })
        
        })

捕捉事件:

EventBus.$on('Logged-Out',() => {
                this.isUserLoggedIn = false
                localStorage.setItem('JWT', '')
            })

            EventBus.$on('Logged-in',() => {
                this.isUserLoggedIn = true
            })

【问题讨论】:

  • 我认为另一个组件应该是您正在导航的组件的父/祖先路由,是这样吗?
  • 原来如此,非常感谢。但是有没有其他方法可以用来在vue的导航守卫中的不同组件之间进行通信
  • 可以使用vue store,看store里面的变化

标签: javascript vue.js vue-component vue-router


【解决方案1】:

问题是我混淆了听者和发声体的创建顺序,听者是在发声体之后创建的,这导致了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2020-08-22
    • 2014-11-12
    • 1970-01-01
    相关资源
    最近更新 更多