Javascript EventBus.$on不';我似乎无法捕捉到正在发出的事件。(Vue js)
当前正在尝试从router.beforeach发出事件,并尝试在我的其他组件中侦听该事件。 但是,尽管vue devtool显示事件实际上正在发出,但我的组件似乎无法捕获它。 先谢谢你 我的EventBus声明:Javascript EventBus.$on不';我似乎无法捕捉到正在发出的事件。(Vue js),javascript,vue.js,vue-component,vue-router,Javascript,Vue.js,Vue Component,Vue Router,当前正在尝试从router.beforeach发出事件,并尝试在我的其他组件中侦听该事件。 但是,尽管vue devtool显示事件实际上正在发出,但我的组件似乎无法捕获它。 先谢谢你 我的EventBus声明: import Vue from 'vue' export const EventBus = new Vue() 启动事件: router.beforeEach((to, from, next) => { console.log('from',from.n
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
})
捕捉事件:
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存储并查看存储中的更改我认为其他组件应该是您导航的组件的父/祖先路径,是这样吗?是这样的,非常感谢。但是我是否可以使用其他方式在vue的导航保护中的不同组件之间进行通信您可以使用vue存储并查看存储中的更改