Nuxt.js createPersistedState不保留存储模块状态

时间:2020-07-19 21:02:30

标签: vue.js vuex nuxt.js vuex-modules

我正在编写我的第一个nuxt.js网站,但插件未保存购物车模块中的数据。 这是我的代码(我已经折叠了不相关的代码)

plugins / localStorage.js

import createPersistedState from 'vuex-persistedstate'
import SecureLS from 'secure-ls'

let ls = new SecureLS({ isCompression: false })

export default async ({
  app, store, $axios, isHMR,
}) => {
  // Just in case nuxt.config.js gets a change in ssr:false when adding this plugin.
  // Notice isClient is deprecated, instead use process.browser.
  if (process.browser) {
    // In case of HMR, mutation occurs before nuxtReady, so previously saved state
    // gets replaced with original state received from server. So, we've to skip HMR.
    // Also nuxtReady event fires for HMR as well, which results multiple registration of
    // vuex-persistedstate plugin
    if (isHMR) return
    createPersistedState()(store) // vuex plugins can be connected to store, even after creation
  }
}

store / index.js

import Vuex from 'vuex';
import Cart from '~/store/cart'    
let store
    
const initStore = () => {
  return store || (store = new Vuex.Store({
    state: {
      status: '',
      token: '',
      tokensExpiry: '',
      tokensExpiryDate: '',
      user: ''
    },
    mutations: { ... },
    actions: { ... },
    getters: { ... },
    modules: {
      cart: Cart
    }
  }))
}

export default initStore

store / cart.js

export const state = () => ({
  pledges: [],
  deliveryMethod: []
})

export const mutations = { ... }

export const getters = { ... }

export default {
  state,
  mutations,
  actions,
  getters
};

nuxt.config.js

...
plugins: [
    { src: '~/plugins/localStorage.js', ssr: false }
],
...

该插件可以轻松存储我的store/index.js中的所有内容,但是每次刷新后,store/cart.js中的所有数据都会丢失。

我在做什么错?我不知道为什么它不起作用。

0 个答案:

没有答案