【发布时间】: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