前端对页面数据进行缓存

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

前端做缓存,一般放在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);
    }
}
相关推荐
Risehuxyc几秒前
C# 将doc转换为docx
开发语言·c#·xhtml
小粉粉hhh2 分钟前
React(三)——Redux
前端·javascript·react.js
易知微EasyV数据可视化1 小时前
定制化3D组件开发:打造差异化孪生体验
前端·人工智能·经验分享·数字孪生
多加点辣也没关系1 小时前
JavaScript|第24章:事件循环与并发模型
开发语言·javascript·ecmascript
ん贤1 小时前
怎么设计,才算一个优秀审计模块
大数据·开发语言·设计·审计
l1t1 小时前
测试用rust重写的postgresql: pgrust
开发语言·postgresql·rust
2501_948106912 小时前
计算机毕业设计之jsp-智慧旅游分享平台
java·开发语言·spark·汽车·课程设计·旅游
前端炒粉2 小时前
Vue2 SSE 流式对话完整前端代码
前端·sse·流式输出
阿里云云原生2 小时前
Agent 不再是“玩具”!AgentScope Java 2.0 GA 发布:构建企业级分布式智能体底座
java·开发语言·分布式·agentscope
BIM云平台开发2 小时前
【App.vue里跟踪页面跳转和用户ID】
开发语言·前端·javascript