0
Please make a functions like below, in some file say helper.js and initialize it in main.js
helper.js
import axios from 'axios';
export function initialize(store, router)
{ router.beforeEach((to,from,next)=>{
const requiresAuth= to.matched.some(record=>record.meta.requiresAuth)
const currentUser = store.state.isAuthenticated;
if(requiresAuth && !currentUser){ next('/signin');}
else if(to.path=='/signin' && currentUser){ next('/')}
else { next()}
})
}
in your main.js
import {initialize} from './helper';
import router from './router'
import store from './store'
initialize(store, router);
Login page
methods: {
...mapActions(["login"]),
loginUser: function(event) {
event.preventDefault();
this.login({ email: this.email, password: this.password })
.then(()=>{ this.$router.replace({name:'dashboard'})
//forward to this path after login
}).catch(()=>{console.log('login fail') });
}
},
-1
You should create store before you use
// auth.js
import Vue from 'vue'
import Vuex from 'vuex'
import router from "../../router";
Vue.use(Vuex)
// ....
export default new Vuex.Store({
state,
getters,
actions,
mutations,
});
Otherwise the auth.getters.isAuthenticated
will be the function, not the vuex getters.
The vuex guide is here https://vuex.vuejs.org/guide/
Source:stackexchange.com