I am new to vue.js and I am facing problem in initializing the router.
When user hits '/' I want to redirect to '/home' if the user has already signed in else redirect him to '/login'. On successful login, I am saving the access token in localStorage. Whenever the user revisits the page, I am fetching the token from localStorage and setting in my vuex store and redirecting him accordingly.
But the problem is even if user is already signed in, it always redirect to '/login' page. The call to router is getting executed before setting the token in store.
Below is my code. Please let me know how can I solve this.
//main.js
import Vue from 'vue';
import Vuetify from 'vuetify';
import App from './App';
import { store } from './store';
import router from './router';
Vue.use(Vuetify);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: { App },
beforeCreate () {
const token = localStorage.getItem('userToken');
this.$store.dispatch('autoSignInToken', token);
}
});
//router.js
import Vue from 'vue';
import Router from 'vue-router';
import Login from '@/components/User/Login';
import Hello from '@/components/Hello';
import AuthGuard from './auth-guard'
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Home',
redirect: '/home',
},
{
path: '/login',
name: 'Login',
component: Login,
beforeEnter: AuthGuard
},
{
path: '/home',
name: 'Home',
component: Hello,
beforeEnter: AuthGuard,
},
],
});
//auth-guard.js
import {store} from '../store'
export default (to, from, next) => {
if (store.getters.user) {
if(to.fullPath === '/login') {
next('/home');
} else {
next();
}
} else {
if(to.fullPath !== '/login') {
next('/login');
} else {
next();
}
}
}
Well, there's not reason that you have to add the token in beforeCreate at all, is there? You don'T access the Vue instance at all, you only work with localStorage and the store.
So just do it before you even create the router.
const token = localStorage.getItem('userToken');
store.dispatch('autoSignInToken', token);
export default new Router({
routes: [
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With