来自VueX和NuxtJS的持久状态

时间:2018-03-23 16:42:58

标签: vuex nuxt.js adonis.js

我使用vuex-persistedstate包(https://github.com/robinvdvleuten/vuex-persistedstate)在浏览器上保留数据状态。

我使用Adonuxt(NuxtJS和AdonisJS之间的混合)。

在VueX操作中,我有这个动作:

nuxtClientInit ({commit}) {
      // I want get here state auth saved by persistedstate package
    }

此操作由插件调用:

localstorage.js

export default async (context) => {
  await context.store.dispatch('nuxtClientInit', context)
}

nuxt.js插件(配置)

{
      src: '~/plugins/localstorage.js',
      ssr: false
    }

我希望get state使用用户令牌配置Axios:

this.$axios.setToken(auth.jwt.token, 'Bearer')

我的印象nuxtClientInit()在persistedstate包之前被调用,因此state.auth为null,但它可以在控制台中观察到:

image

3 个答案:

答案 0 :(得分:1)

我已使用https://www.npmjs.com/package/vuex-persist来保留来自Vuex的数据。

答案 1 :(得分:0)

就我而言,我在指定目录时犯了一个错误。

root/
 ├ src/
 ├ pages/
     .
     .
 ├ src/
   └ plugins/
     └ localstorage.js/

在上述目录中,必须指定如下。

在 nuxt.config.js 中

{src:'~/src/plugins/localstorage.js', srr: false}

答案 2 :(得分:0)

csr+ssr cookie

您可以选择以下任一库

1 .vuex-persistedstate

2 .vuex-persist

vuex-persistedstate 使用

https://www.npmjs.com/package/vuex-persistedstate

plugins/persistedstate.js

import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

export default ({store, req, isDev}) => {
  createPersistedState({
      key: 'your_key',
      paths: ['state1', 'state2',...so_on],
      storage: {
        getItem: (key) => process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],
        setItem: (key, value) => Cookies.set(key, value, { expires: 365, secure: !isDev }),
        removeItem: (key) => Cookies.remove(key)
      }
  })(store)
}

nuxt.config.js

  plugins: [
      { src: '~plugins/persistedstate.js' }
    ]

vuex 持久化

https://www.npmjs.com/package/vuex-persist

// ~/plugins/vuex-persist.js
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

import VuexPersistence from 'vuex-persist'

export default ({ store, req, isDev }) => {
  new VuexPersistence({
    key:'test',
    reducer: (state) => ({}),
    restoreState: (key, storage) =>process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie||'')[key],
    saveState: (key, state, storage) =>
    Cookies.set(key, value, { expires: 365, secure: !isDev }),

  }).plugin(store);
}

nuxt.config.js

 plugins: [
      { src: '~plugins/vuex-persist.js' }
    ]