【问题标题】:Vuex-persistedstate does not work after refreshing a page刷新页面后Vuex-persistedstate不起作用
【发布时间】:2020-02-15 16:13:19
【问题描述】:

我正在用 laravel 和 vue 制作一个 spa 应用,我想在刷新页面后将我的登录信息保持在 vuex 的状态。

我输入了

sudo npm install vuex-persistedstate

并安装了 Vuex-persistedstate 并设置插件如下。

import Vue from 'vue' import Vuex from 'vuex'

import auth from './auth'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        auth,
        plugins: [createPersistedState()],
    }
})

export default store

我希望在刷新页面后保留我的数据,但事实并非如此。

我检查了发生了什么,插件对象似乎是空的。

似乎由于某种原因我无法导入插件,但我不知道为什么。 有人可以帮帮我吗?

我的模块文件

const state = {
    user: null,
    salonId: null
}

const getters = {
    check: state => !! state.user,
    checkSalonId: state => {return state.salonId},
}

const mutations = {
    setUser (state, user) {
        state.user = user
    },
    setSalonId (state, salonId) {
        state.salonId = salonId
    }
}

const actions = {
    async currentUser (context) {
        const response = await axios.get('/api/user')
        const user = response.data || null
        context.commit('setUser', user)
    },
    async logout (context) {
        context.commit('setUser', null)
        context.commit('setSalonId', null)
    },
    async currentSalon (context, salonId) {
        context.commit('setSalonId', salonId)
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
}

【问题讨论】:

  • 这就是我的意思。你在质疑,但不关心答案。
  • 抱歉,我只是没有注意到您的回答。由于某种原因没有通知我。我总是回复答案。感谢您的回答。我一直在想这个。
  • 哈哈,好的,我现在看到了。感谢您的关注????

标签: vue.js


【解决方案1】:

您将plugins 放置在错误的位置。 plugins 应该与modules 内联,而不是在modules 内。

请看看这些差异。

const store = new Vuex.Store({
    modules: {
        auth,
        plugins: [createPersistedState()]
    }
})

VS

const store = new Vuex.Store({
    modules: {
        auth
    },
    plugins: [createPersistedState()]
})

【讨论】:

    【解决方案2】:

    我认为您需要使用要保留的模块设置一个选项对象。在这个例子中,我从我的商店中持久化用户模块(没有包含导入代码)

    const persistedStateOptions = {
      paths: [
        'user',
      ]
    }
    
    export default new Vuex.Store({
      modules: {
        user,
      },
      plugins: [createPersistedState(persistedStateOptions)]
    })
    

    【讨论】:

    • 试过了,还是不行。看来问题不在于路径..
    【解决方案3】:

    看看路径的差异。这对我有用。

    import createPersistedState from 'vuex-persistedstate';
        Vue.use(Vuex);
    
       export default    new Vuex.Store({
       strict:true,
        modules:{
        party,
        contract
       },
       plugins: [createPersistedState(
        {
            paths:['party.selectedParty']
        }
      )],
       });
    

    其中party 是模块名称,selectedParty 是模块状态的名称。 现在这个插件只处理 selectedParty 状态。 通过状态从 DB 获取数据的 vue 组件应该远离这个插件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 2016-08-15
      • 2014-08-23
      • 2019-02-24
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多