Reputation: 2358
I have this route in my vue router.js file .
routes: [{
path: "/",
component: Home,
beforeEnter: (to, from, next) => {
if (!store.state.is_login) {
next('/login')
}
next()
}
}]
I use beforeEnter option for redirecting user if store.state.is_login === true
first problem : so when I enter the url in browser I will redirect to /login page. this is works fine. but when I click the logo button, this beforeEnter function is not working. this is my button that uses :
<router-link to="/" class="bp-logo"><Logo />home</router-link>
the second problem is :
problem :
condition 1: if !is_login redirect to /login .
condition 2 : if token exists and !is_login => request to backend /user with token and get user_info and set is_login true.
condition 3 : if !is_login && !token redirect to /login
Upvotes: 0
Views: 545
Reputation: 2358
I figured it out somehow. the first problem was when you render a route .then you are click for getting to that route again the function router.beforeEach not trigger. so I find another method in documentation.
routes: [{
path: "/",
component: Home,
beforeEnter: isAuthenticated,
}]
and this is my custom function for handling both problems .
const isAuthenticated = (to, from, next) => {
if (!store.state.is_login) {
if ((localStorage.getItem('token')) && (lodash.isEmpty(store.state.user))) {
let headers = {
headers: {
Authorization: localStorage.getItem("token"),
"Access-Control-Allow-Origin": "*"
}
};
axios
.get(`${store.state.api}admin/user`, headers)
.then(response => {
store.state.user = response.data.user;
store.state.is_login = true;
next("/");
})
.catch(error => {
store.state.Error = error;
next('/login')
});
}
next('/login')
return
}
next()
return
}
Upvotes: 0
Reputation: 1458
You need to change your beforeEnter
method to access the store instance. Rewrite like this:
beforeEnter: (to, from, next) => {
if (!this.$store.state.is_login) {
next('/login')
}
next()
}
Upvotes: 1