4

在第一页刷新时,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之前保留本地存储中的相关存储条款?

4

1 回答 1

6

You can't do this. Its impossible. There is no localstorage on server. And asyncData executed on server on first load/refresh. So there is no way to get data from in asyncData from localstorage on server even theoretically.

于 2019-07-14T21:06:26.210 回答