我想在 Nuxt.js 中的 Vuex 中使用 window.localStorage

I want to use window.localStorage in Vuex in Nuxt.js

我正在开发 nuxt.js 应用程序。重点是登录和注销。


我们将开发一个JWT系统的登录。

您必须在 vuex 中保持登录状态。

但是,当我刷新页面时,vuex 被初始化了。

我读过 git vuex-persistedstate ,但很难理解如何初始化和设置它。

在 nuxt.js 中开发登录系统的最佳方法是什么?

谢谢。

使用 vuex-persisted state 将是您场景的最佳用例。

我将带您完成使用 vuex-persisted state 的过程。

  1. 打开命令行,cd到你的项目目录,然后输入npm install --save vuex-persistedstate。这会将 vuex-persistedstate 安装到您的项目 dependencoes 中。
  2. 现在,在您的 store.js 文件中或您定义 vuex 存储的任何地方,添加 vuex-persistedstate 插件
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    user: {
      name: "john doe",
      age: " 16",
    },
    loggedIn: false,
    hobbies: ["eating", "partying"],
  },
  plugins: [
    createPersistedState({
      paths: ["user", "loggedIn"],
      getState: (key) => Cookie.getJSON(key),
      setState: (key, state) =>
        Cookie.set(key, state, { expires: 1, secure: false }),
    }),
  ],
});

  1. 您还需要 js-cookie 包,它可以更轻松地处理 cookie。使用 npm install --save js-cookie.
  2. 路径属性表示要持久化状态的哪些部分,在我们的例子中保存为cookies.If没有给出路径属性,那么整个状态被持久化
  3. 从上面的例子中我们提到了路径 paths: ['user', 'loggedIn'],所以只有 userloggedIn 状态的属性是保存在 cookie 中而不是 hobbies.
  4. 如果您在商店中使用模块,定义持久化拍拍的方式如下:
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";

import myModule from "./myModule";
import myAnotherModule from "./myAnotherModule";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    user: {
      name: "john doe",
      age: " 16",
    },
    loggedIn: false,
    hobbies: ["eating", "partying"],
  },
  modules: {
    myModule,
    myAnotherModule,
  },
  plugins: [
    createPersistedState({
      paths: ["user", "loggedIn", "myModule.<nameOfThePropretyInState>"],
      getState: (key) => Cookie.getJSON(key),
      setState: (key, state) =>
        Cookie.set(key, state, { expires: 1, secure: false }),
    }),
  ],
});
  1. 在您的路径中,您将在您想要保留的状态中引用模块的 属性。在上面的示例中,您提到的 myModule 状态的 属性 被持久化。 myAnotherModule 状态未保存,因为路径中未提及。

  2. 就是这样。如果您想自定义使用 vuex-persisted statejs-cookie 的方式,请查看它们的文档。

  3. 如果您想检查您想要的状态是否保存在 cookie 中,那么您可以像这样控制台记录您的 cookie:console.log(document.cookie 在您的 App.vue created() 生命周期钩子

我改用 vuex-persist 包,很容易上手 运行ning。这也适用于 SSR。

import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'

Vue.use(Vuex)
let vuexLocalStorage = null;

if (process.browser) {

    vuexLocalStorage = new VuexPersist({
      key: 'vuex', // The key to store the state on in the storage provider.
      storage: window.localStorage, // or window.sessionStorage or localForage
    })
}

export function createStore() {
    return new Vuex.Store({
        state: {
        
        },
        actions,
        mutations,
        getters,
        plugins: process.browser ? [vuexLocalStorage.plugin] : []
    })
}

只需确保在浏览器中将所有内容设置为 运行

我强烈建议在 nuxt 和 vuex 商店中使用 cookie 而不是 localStorage。使用诸如 univeral-cookie 之类的包和内置的 nuxtServerInit 操作,您可以通过读取来自服务器的初始请求的 cookie 来填充客户端和服务器存储。您可以使用 cookie 存储的数据量可能会受到限制,但如果您实施 RESTful-like API 并尽可能将 id 存储在您的 cookie 中,您可以在服务器端获取该数据以填充完整的堆栈存储,从而在用户刷新页面的情况下很好地设置自己。我发现 auth 令牌也非常方便,它们会根据自己的 cookie 相关行为过期,因此在页面刷新的情况下不会存在于商店中(或其突变处理的解码数据)。

最好使用 cookie 来保存授权令牌,看看这个 nuxt 模块

https://github.com/microcipcip/cookie-universal/tree/master/packages/cookie-universal-nuxt

这里是 vuex store 模块设置 cookie 的例子

//call async ajax request to get UUID
const uuidReq = await dispatch('getUUID')

if (uuidReq.hasOwnProperty('meta')) {
  commit('setState', {
    uuid: uuidReq.meta.links.me.meta.id,
    isLogin: true
  })

  // calculate expires
  const expDate = new Date()
  expDate.setTime(expDate.getTime() + (state.accExpKey - 0.3) * 1000)
  const expDate2 = new Date()
  expDate2.setTime(expDate.getTime() + 2592000 * 1000)

  const options = {
    path: '/',
    expires: expDate
  }
  const options2 = {
    path: '/',
    expires: expDate2
  }

  const cookieList = [{
      name: 'g_isLogin',
      value: true,
      opts: options2
    },
    {
      name: 'g_accKey',
      value: state.accKey,
      opts: options
    },
    {
      name: 'g_refKey',
      value: state.refKey,
      opts: options2
    },
    {
      name: 'g_userUUID',
      value: uuidReq.meta.links.me.meta.id,
      opts: options
    }
  ]
  this.$cookies.setAll(cookieList)
}

自定义 Nuxt 中间件的示例实现检查现有的 cookie,然后将它们注入 vuex 状态

export default function({ store, route, redirect, app }) {
  const isLogin = app.$cookies.get('g_isLogin') === 'true'
  const accKey = app.$cookies.get('g_accKey') || ''
  const refKey = app.$cookies.get('g_refKey') || ''
  const userUUID = app.$cookies.get('g_userUUID') || ''

  // console.warn('authenticated isLogin:', isLogin)

  // If the user authenticated
  if (isLogin) {
    store.commit('user/setState', {
      isLogin: isLogin,
      accKey: accKey,
      refKey: refKey,
      uuid: userUUID
    })
  } else {
    return redirect('/?prevURL=' + route.path)
  }
}

要在 nuxt 客户端和服务器中使用 vuex-persistedstate,请按照以下步骤操作。

例如,假设您有一个 Vuex Module user 并且您想要保留它。即使您 refreshroute 到另一个页面。

const user = {
    namespaced: true,
    state: () => ({
        name: 'geeekfa'
    }),
    mutations: {
        name(state, name) {
            state.name = name;
        },
    },
    getters: {
        name: (state) => {
            return state.name;
        },
    }
}
export default user
  1. 安装 vuex-persistedstate

npm install --save vuex-persistedstate

  1. 安装 cookie 和 js-cookie

npm install --save cookie js-cookie

在那之后你的 package.json 就像:

  "dependencies": {
    ...
    "cookie": "^0.3.1",
    "js-cookie": "^2.2.1",
    "vuex-persistedstate": "^4.0.0-beta.3",
    ...
  }
  1. ~/plugin/persistedState.js
  2. 中创建 persistedState.js
// persistedState.js
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

export default ({ store, req }) => {
  createPersistedState({
    paths: ['user'], // your vuex module name
    storage: {

      getItem: (key) => {
        if (process.server) {
          const parsedCookies = cookie.parse(req.headers.cookie)
          return parsedCookies[key]
        } else {
          return Cookies.get(key)
        }
      },
   
      setItem: (key, value) =>
        Cookies.set(key, value, { expires: 365, secure: false }),
      removeItem: key => Cookies.remove(key)
    }
  })(store)
}
  1. 将此插件添加到 nuxt.config.js
plugins: [
    ...
    { src: '~/plugins/persistedState.js' }
    ...
  ],

这就够了!即使在客户端和服务器端刷新后,您也可以保留 user 模块。有 不需要更改 ~/store/index.js 文件