Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex state not preserved after page redirect

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},  
]
like image 990
Karlom Avatar asked Dec 07 '22 16:12

Karlom


1 Answers

Vuex state is kept in memory. If you redirect with window.location.href this will trigger a full page load, which will purge your current state. You have to use Vue router to do your navigation https://router.vuejs.org/en/

For example if your route name is Home you can redirect like this:

this.$router.push({ name: 'Home' });
like image 51
Florian Haider Avatar answered Dec 10 '22 07:12

Florian Haider