【问题标题】:Managing Vuex state using with NuxtJs on 'universal' mode在“通用”模式下使用 NuxtJs 管理 Vuex 状态
【发布时间】:2018-11-17 05:59:11
【问题描述】:

我习惯于在 Vuex 中使用 localStorage,但正如你所知,在 SSR 上我们不能使用 localeStorage。所以我搜索了一个解决方案,让 Vuex state 保持页面刷新并多次使用 js-cookie 遇到 vuex-persistedstate。 我的问题是我真的需要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)
}

等等

【问题讨论】:

  • 我在 nuxt 中使用 cookie,而我从未使用过 vuex-persistedstate。甚至从未听说过。我使用 'js-cookie' 来设置 cookie 和 'cookie' 来获取它们。就像我学到的一样。
  • @Andrew1325 所以我可以像上面的例子一样使用?

标签: vuex nuxt.js


【解决方案1】:

关注您的评论问题。您在问题中的示例至少可以设置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'

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

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 2018-08-18
    • 2020-06-05
    • 2021-01-27
    • 2021-08-18
    • 1970-01-01
    • 2018-09-02
    • 2019-11-27
    • 1970-01-01
    相关资源
    最近更新 更多