页面录入信息,退出且未提交状态下,前端对页面数据进行存储
前端做缓存,一般放在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);}
}