【问题标题】:Nuxt.js with vuex-persist - persisted state not available in asyncData upon page refresh带有 vuex-persist 的 Nuxt.js - 页面刷新时 asyncData 中的持久状态不可用
【发布时间】:2019-11-23 15:22:13
【问题描述】:

在第一页刷新时,asyncData 函数无法获取持久状态。当我关注另一个 NuxtLink 并返回此页面时,同时状态没有发生变化,数据就在那里。这意味着持久状态在第一次加载/刷新时在服务器端不可用。 LocalStorage 是我选择保存相关状态项的地方。

使用 asyncData 的页面组件:

  asyncData({ app, params, store }) {
  //its not available upon first refresh, but is after following a random nuxtlink and going back
    const cartProducts = store.getters.getCartProducts 
},

store/index.js 很简单。不幸的是,在第一页刷新时,asyncData 中的状态完全为空。

  getCartProducts(state) {
    return state.cart.products
  },

按照 Github 自述文件中的建议,使用模式“客户端”正确导入 vuex-persist.js

import VuexPersistence from 'vuex-persist'
/** https://github.com/championswimmer/vuex-persist#tips-for-nuxt */

export default ({ store }) => {
  window.onNuxtReady(() => {
    new VuexPersistence({
      key: 'cartStorage'
      /* your options */
    }).plugin(store)
  })
}

如何确保本地存储中的相关存储条款在调用 asyncData 之前保留?

【问题讨论】:

    标签: vuex nuxt.js vue-ssr


    【解决方案1】:

    你不能这样做。不可能。服务器上没有localstorage。并且asyncData 在第一次加载/刷新时在服务器上执行。因此,即使在理论上,也无法从服务器上的localstorage 中的asyncData 中获取数据。

    【讨论】:

    • 因此对于购物车类型的实现来说,使用状态并不是正确的决定。服务器会话应该可以正常工作。 SSR的概念还是让我很困惑,再次感谢您的回答。
    • @ViBoNaCci 是的,一开始可能会令人困惑。是的,如果可以的话,将服务器上的购物车内容绑定到帐户会更好。对于客户端持久性,只能使用 cookie。例如。 vuex 的一些自定义模块,使用 Universal-cookie 作为存储选项或 nuxt-universal 存储包
    • 查看nuxtServerInit,了解如何在服务器负载时将服务器数据填充到存储中。你也可以从asyncData访问req/res
    猜你喜欢
    • 2017-08-19
    • 2020-12-01
    • 2020-03-11
    • 2021-06-19
    • 2018-01-20
    • 2021-03-20
    • 1970-01-01
    • 2022-11-11
    • 2021-11-14
    相关资源
    最近更新 更多