前端对页面数据进行缓存

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

前端做缓存,一般放在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);
    }
}
相关推荐
jiayong231 分钟前
第 33 课:任务看板视图(按状态分列)与本地持久化
开发语言·前端·javascript·学习
A_aspectJ11 分钟前
【Java基础开发】 基于Swing GUI 组件实现图书管理系统
java·开发语言
GISer_Jing14 分钟前
Dify可视化编排:技术架构与实战指南
前端·人工智能·ai编程
宇宙realman_99921 分钟前
DSP28335-FlashAPI使用
linux·前端·python
xyq202425 分钟前
Font Awesome 加载中图标
开发语言
踩着两条虫1 小时前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构
Yeats_Liao1 小时前
后台 Sidebar 伸缩交互(PC + 移动端)实现
前端·javascript·css·html5
MXN_小南学前端1 小时前
computed 计算属性详解:触发时机、实战场景、Vue2 与 Vue3 对比
前端·javascript·vue.js
isNotNullX1 小时前
数据大屏怎么做?数据大屏有哪四个核心环节
开发语言·前端·javascript
Hello eveybody1 小时前
介绍最大公因数和最小公约数(C++)
java·开发语言·c++