4
votes

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},  
]
2
Do you use Vue router?str
Yes I do use vue router.Karlom
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 with localStorage for nowPhil

2 Answers

14
votes

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' });
0
votes

Use Vuejs to navigate between the pages, don't do it manually

Unless you navigate from one page to another using Vuejs routes, state will not be preserved. Consider these two scenarios

  1. After setting the state in the store from one page. You enter the URL for another page directly in to the browser window and hit enter. Check the state in the store. It will not be preserved and will be reset to default values.
  2. After setting the state in the store from one page. You navigate to the another page using Vuejs route

In Nuxtjs

<nuxt-link to="discussion/1">Go to Discussion</nuxt-link>

In Vuejs

<router-link to="discussion/1">Go to Discussion</router-link>

Check the state in the store. It will be preserved in the store.