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

Kar*_*lom 2 javascript vue.js vuex

在Vue.js中,我有此方法可以登录用户,将值设置为in 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     
          }
Run Code Online (Sandbox Code Playgroud)

突变示例:

setToken: function (state, token) {
    state.token = token;
    },
setUsername: function (state, username) {
    state.username = username;
},
Run Code Online (Sandbox Code Playgroud)

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

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

    token () {
        return this.$store.state.token; 
    } ,
Run Code Online (Sandbox Code Playgroud)

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

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

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},  
]
Run Code Online (Sandbox Code Playgroud)

Flo*_*der 6

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

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

this.$router.push({ name: 'Home' });
Run Code Online (Sandbox Code Playgroud)

  • 我添加了 `this.$router.push({ path: '/home' });` 现在它就像一个魅力。谢谢! (2认同)