前端对页面数据进行缓存

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

前端做缓存,一般放在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);
    }
}
相关推荐
yong99909 分钟前
基于MATLAB的随机振动界面设计与功率谱密度分析实现
开发语言·matlab
eason_fan12 分钟前
从一则内存快照看iframe泄漏:活跃与Detached状态的回收差异
前端·性能优化
超级种码17 分钟前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
天天向上102420 分钟前
go 配置热更新
开发语言·后端·golang
狗头大军之江苏分军30 分钟前
年底科技大考:2025 中国前端工程师的 AI 辅助工具实战盘点
java·前端·后端
晨晖235 分钟前
顺序查找:c语言
c语言·开发语言·算法
wadesir44 分钟前
C++非对称加密实战指南(从零开始掌握RSA加密算法)
开发语言·c++
编程修仙1 小时前
第三篇 Vue路由
前端·javascript·vue.js
a程序小傲2 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
比老马还六2 小时前
Bipes项目二次开发/硬件编程-设备连接(七)
前端·javascript