在 'universal' 模式下使用 NuxtJs 管理 Vuex 状态

Managing Vuex state using with NuxtJs on 'universal' mode

我习惯在 Vuex 中使用 localStorage 但正如你所知,在 SSR 上我们不能使用 localeStorage。所以我搜索了一个解决方案,让 Vuex state 在页面刷新时保持 运行 进入 vuex-persistedstatejs-cookie 多次使用。 我的问题是我真的需要 vuex-persistedstate 吗?我的意思是我可以像下面这样使用 js-cookie 吗:

import Cookie from 'js-cookie'

const state = {
  firstName: Cookie.get('firstName)
}

const mutations = {
  setFirstName(state, name) {
    state.firstName = name;
    Cookie.set('firstName', name)
}

等等

按照你的评论提问。您在问题中的示例至少可以设置 cookie。我首先将我的设置为一个动作,然后提交突变以仅设置状态。至于获取 cookie,您可能需要的不仅仅是设置状态。正如我所说,我使用 'cookie' (see here) 获取我的 cookie,我通过 nuxtServerInit 获取它们,如下所示:

nuxtServerInit({dispatch}, context) {
              return Promise.all([
                dispatch('get_cookies', context),
                //other actions
              ]);
            },

动作本身如下:

get_cookies (vuexContext, context) {
              return new Promise((resolve, reject) => {
                const cookieConst = cookie.parse(context.req.headers.cookie || '')
                if (cookieConst.hasOwnProperty('YourCookieName')) {
                    //commit mutations here
                }
                else {
                    resolve(false)
                }
              })
            },

显然你需要导入:

import cookies from 'js-cookie'
import cookie from 'cookie'

你可以在cookies中放一些东西,我设置用户详细信息和购物车。我还在我的 cookie 中存储了一个访问令牌,并在我的后端对其进行了验证,这样我就可以保持身份验证状态。