前端对页面数据进行缓存

页面录入信息,退出且未提交状态下,前端对页面数据进行存储

前端做缓存,一般放在local、session和cookies里面,但是都有大小限制,如果页面东西多,比如有上传的图片、视频,浏览器会抛出一个QuotaExceededError错误。所以最后采用了vuex进行存储
思路:进入页面时,会请求接口获取数据,判断该条数据是否在vuex里面进行存储,如果有,将vuex中的值赋值给form,如果没有,将接口返回的值赋值给form。提交时,在vuex中清楚该数据。点击返回按钮时,在生命周期钩子beforeDestory中对页面数据进行存储
arrList:this.$store.state.cachedData //vuex 缓存的页面数据
form:{} // 页面v-model的数据
id:当前页面数据的唯一标识
复制代码
 import { mapState, mapMutations } from "vuex";  


 computed: {
    ...mapState(["cachedData"]),
  },

methods:{
    ...mapMutations(["setCachedData"])
}

  beforeDestroy() {
    //有多条数据,根据唯一标识id进行存取和清除
    let dataToCache = {
      id: this.id,
      data: JSON.stringify(this.form),
    };
    const index = this.arrList.findIndex(
      (item) => item.id == this.id
    );
    if (index != -1) {
      this.arrList[index] = dataToCache;
    } else {
      this.arrList.push(dataToCache);
    }
    this.setCachedData(this.arrList);
  },

mounted(){
    this.getPageDate()
},
methods:{
    getPageDate(){
            //都接口,获取当前页面数据,判断缓存中是否有该条数据
           const index = this.arrList.findIndex(
              (item) => item.id == this.id
            );
            if (index !== -1) {
              this.form = JSON.parse(
                this.$store.state.cachedData[index].data
              );
            } else {
                this.form = res.data.list
              }

    },
    submit(){
          //走接口,提交成功时,进行清除
           const index = this.arrList.findIndex(
                (item) => item.id == this.id
              );
            this.arrList.splice(index, 1);
            this.setCachedData(this.arrList);
    }
}
相关推荐
兮动人3 分钟前
Java应用全链路故障排查实战指南:从系统资源到JVM深度诊断
java·开发语言·jvm
R-sz13 分钟前
导出word并且插入图片
开发语言·c#·word
CodeWithMe14 分钟前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
脑袋大大的32 分钟前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
军军君0141 分钟前
基于Springboot+UniApp+Ai实现模拟面试小工具二:后端项目搭建
前端·javascript·spring boot·spring·微信小程序·前端框架·集成学习
Wy. Lsy1 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
quweiie1 小时前
tp8.0\jwt接口安全验证
前端·安全·jwt·thinkphp
Tanecious.2 小时前
C++--红黑树
开发语言·c++
xiaoyan20152 小时前
最新Flutter3.32+Dart3仿微信App聊天实例
前端·flutter·dart
Top`2 小时前
Java 泛型 (Generics)
java·开发语言·windows