ViB*_*Cci 4 vuex nuxt.js vue-ssr
刷新第一页时,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
},
Run Code Online (Sandbox Code Playgroud)
store/index.js 很简单。不幸的是,在第一页刷新时,asyncData 中的状态完全为空。
getCartProducts(state) {
return state.cart.products
},
Run Code Online (Sandbox Code Playgroud)
按照 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)
})
}
Run Code Online (Sandbox Code Playgroud)
如何确保在调用 asyncData之前保留本地存储中的相关存储术语?
你不能这样做。不可能。localstorage服务器上没有。并asyncData在第一次加载/刷新时在服务器上执行。因此,即使在理论上,也无法从asyncData服务器localstorage上获取数据。
| 归档时间: |
|
| 查看次数: |
4713 次 |
| 最近记录: |