首页 > 解决方案 > 刷新页面后Vuex-persistedstate不起作用

问题描述

我正在用 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

解决方案


你放plugins错地方了。plugins应该是 inline with modules,而不是 inside modules

请看一下这种差异。

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

VS

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

推荐阅读