页面重定向后 Vuex 状态未保留

Vuex state not preserved after page redirect

在 Vue.js 我有这个方法来登录用户,设置值 int vuex store 然后重定向到主页:

   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     
          }

示例突变:

setToken: function (state, token) {
    state.token = token;
    },
setUsername: function (state, username) {
    state.username = username;
},

App.vue(根组件),我只是从存储中获取值作为计算值:

  computed: {
    isAuthenticated () {
    return this.$store.state.isAuthenticated;
    },

    token () {
        return this.$store.state.token; 
    } ,

当我注释掉 window.location.href = '/home'; 时,我在 Vue.js 控制台中看到登录成功并且在商店中设置了值,但是一旦页面被重定向到 /home所有存储值都被清空。 我想知道为什么会发生这种情况以及如何解决它?

更新: 我在这样的 routes.js 中使用 vue-router:

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},  
]

Vuex 状态保存在内存中。如果您使用 window.location.href 重定向,这将触发整页加载,这将清除您的当前状态。您必须使用 Vue 路由器来进行导航 https://router.vuejs.org/en/

例如,如果您的路由名称是 Home,您可以这样重定向:

this.$router.push({ name: 'Home' });

使用Vuejs在页面之间导航,不要手动做

除非您使用 Vuejs 路由从一个页面导航到另一个页面,否则不会保留状态。考虑这两种情况

  1. 从一页设置商店中的状态后。您直接在浏览器 window 中输入另一个页面的 URL,然后按回车键。检查商店中的状态。它不会被保留,将被重置为默认值。
  2. 从一页设置商店中的状态后。您使用 Vuejs route
  3. 导航到另一个页面

在 Nuxtjs 中

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

在 Vuejs 中

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

查看商店中的状态。会保留在店里。