nuxt中刷新页面后防止store值丢失

1、 配置插件()

plugins: [
    {src:'~/plugins/storeCache',ssr: false},
  ],

注意:要禁止服务端运行,不然会报错,这个事件是在客户端添加的,不是在服务端小渲染的时候添加的。

2 。在plugins/storeCache.js

写代码,如下。

export default function(ctx){
    //离开页面 刷新前 将store中的数据存到session
    window.addEventListener('beforeunload', ()=> {
        sessionStorage.setItem("storeCache",JSON.stringify(ctx.store.state))
    });
    //页面加载完成  将session中的store数据
    window.addEventListener('load', ()=> {
        let storeCache = sessionStorage.getItem("storeCache")
        if(storeCache){
            // 将session中的store数据替换到store中
            ctx.store.replaceState(JSON.parse(storeCache));
        }
    });
}

大功告成

猜你喜欢

转载自www.cnblogs.com/fqh123/p/12547848.html