前端对页面数据进行缓存

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

前端做缓存,一般放在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);
    }
}
相关推荐
arvin_xiaoting1 小时前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning
工程师老罗2 小时前
Image(图像)的用法
java·前端·javascript
早點睡3903 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-swiper
javascript·react native·react.js
globaldomain3 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
沈阳信息学奥赛培训3 小时前
#undef 指令 (C/C++)
c语言·开发语言·c++
2401_873204653 小时前
分布式系统安全通信
开发语言·c++·算法
jump_jump3 小时前
深入 JavaScript Iterator Helpers:从 API 到引擎实现
javascript·性能优化
swipe4 小时前
把 JavaScript 原型讲透:从 `[[Prototype]]`、`prototype` 到 `constructor` 的完整心智模型
前端·javascript·面试
问道飞鱼4 小时前
【前端知识】React 组件生命周期:从底层原理到实践场景
前端·react.js·前端框架·生命周期
Dxy12393102164 小时前
JS发送请求的方法详解
开发语言·javascript·ecmascript