我目前在查找路由器代码中的错误时遇到麻烦,该错误以前曾起作用,但我不知道何时或如何破坏它。我已经签入了旧版本,但似乎没有更改。问题是,即使我从路由器中的beforeEach Hook中删除所有代码,并且仅使用console.log()语句,控制台中也不会打印任何内容,因此我的auth-guard无法正常工作。我尝试根据以下命令更改顺序:https://forum.vuejs.org/t/router-beforeeach-if-manually-input-adress-in-browser-it-does-not-work/12461/3,但没有任何更改。
我有以下代码:
router / index.js
router.beforeEach = (to, from, next) => {
console.log('he?')
const currentUser = Firebase.auth().currentUser
const isGold = store.getters['user/isGold']
const requiresAuth = to.matched.some(route => route.meta.requiresAuth)
const requiresGold = to.matched.some(route => route.meta.requiresGold)
console.log(requiresGold, isGold, 'halloooooooo?')
if (currentUser && to.name === 'Login') {
next('/dashboard')
}
if (requiresGold && !isGold) {
console.log('trigger')
}
if (requiresAuth && !currentUser) {
next('/login')
} else {
next(false)
}
}
main.js
Firebase.auth().onAuthStateChanged(user => {
if (user) {
const getToken = () => {
return user.getIdToken(true).then(token => {
store.dispatch('user/setToken', token)
})
}
getToken().then(() => {
store.dispatch('user/setUser')
setInterval(getToken, 3540 * 1000)
})
}
new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: { App }
})
})
在此先感谢您的帮助!
答案 0 :(得分:1)
您未分配给router.beforeEach
。 router.beforeEach
是一种方法,您可以通过函数来调用它。 ({docs)这是您应该使用路由器导航防护的方法:
router.beforeEach((to, from, next) => {
console.log('he?')
const currentUser = Firebase.auth().currentUser
const isGold = store.getters['user/isGold']
const requiresAuth = to.matched.some(route => route.meta.requiresAuth)
const requiresGold = to.matched.some(route => route.meta.requiresGold)
console.log(requiresGold, isGold, 'halloooooooo?')
if (currentUser && to.name === 'Login') {
next('/dashboard')
}
if (requiresGold && !isGold) {
console.log('trigger')
}
if (requiresAuth && !currentUser) {
next('/login')
} else {
next(false)
}
});