Nuxt.js 使用 vuex-persist - 页面刷新时,持久化状态在 asyncData 中不可用
Nuxt.js with vuex-persist - persisted state not available in asyncData upon page refresh
刷新第一个页面后,asyncData 函数无法获取持久状态。当我关注另一个 NuxtLink 并返回到此页面时,同时状态没有发生变化,但数据就在那里。这意味着持久状态最初在服务器端不可用 load/refresh。 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
},
vuex-persist.js 按照 Github 自述文件
中的建议使用模式 'client' 正确导入
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 之前保留来自本地存储的相关存储条款?
你不能这样做。不可能。服务器上没有 localstorage
。 asyncData
首先在服务器上执行 load/refresh。因此,即使在理论上,也无法从服务器上的 localstorage
中的 asyncData
中获取数据。
刷新第一个页面后,asyncData 函数无法获取持久状态。当我关注另一个 NuxtLink 并返回到此页面时,同时状态没有发生变化,但数据就在那里。这意味着持久状态最初在服务器端不可用 load/refresh。 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
},
vuex-persist.js 按照 Github 自述文件
中的建议使用模式 'client' 正确导入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 之前保留来自本地存储的相关存储条款?
你不能这样做。不可能。服务器上没有 localstorage
。 asyncData
首先在服务器上执行 load/refresh。因此,即使在理论上,也无法从服务器上的 localstorage
中的 asyncData
中获取数据。