Router: check auth before render
router.beforeEach((to, from, next) => {
const requireAuth = to.meta.auth
if (requireAuth && store.getters['auth/isAuthenticated']) {
next()
} else if (requireAuth && !store.getters['auth/isAuthenticated']) {
next({name: 'login'})
} else if (!requireAuth && store.getters['auth/isAuthenticated']) {
next({name: 'admin'})
} else {
next()
}
})
Vuex:
state() {
return {
isAuth: false,
user: null,
emailFormFactor: ''
}
},
getters: {
isAuthenticated(state) {
return state.isAuth
},
getEmailFormFactor(state) {
return state.emailFormFactor
},
getUser(state) {
return state.user
}
}
App
onBeforeMount(
() => {
if (localStorage.getItem('auth-token')) {
store.dispatch('auth/checkAuth')
}
}
)
Before,i hve to check the validity of the token and after that, if there is a change of state. Does it need to be tracked in the router? Thanks