In a Vue.js I have this method to login users, set the values int vuex store and then redirect to home page:
login: function () {
axios.post( this.BASE_URL + "/login", {
username: this.username,
password: this.password,
}).then( (res) => {
this.$store.commit('setIsAuthenticated', true);
this.$store.commit('setToken', res.data.token);
this.$store.commit('setPhoto', res.data.photo);
this.$store.commit('setUsername', res.data.username);
window.location.href = '/home'; //<-The problem
}
Example mutations:
setToken: function (state, token) {
state.token = token;
},
setUsername: function (state, username) {
state.username = username;
},
At App.vue
(the root component), I just get values from the store as computed values:
computed: {
isAuthenticated () {
return this.$store.state.isAuthenticated;
},
token () {
return this.$store.state.token;
} ,
When I comment out window.location.href = '/home';
I see in Vue.js console that the login is successful and values are set in the store, However as soon as the page is redirected to /home
all store values are emptied.
I'm wondering why this happens and how to fix it?
UPDATE:
I'm using vue-router in a routes.js
like this:
import webLogin from './components/webLogin.vue';
import showAll from './components/showAll.vue';
export default [
{path:'/', component: showAll },
{path:'/add', component: addJoke } ,
{path: '/login', component: webLogin},
]
window.location.href
loads an entirely new page. If you need the data to be available across page requests, you'll need to persist it somewhere. I'd go withlocalStorage
for now – Phil