提到缓存,第一反应就是keep-alive,奈何keepalive的坑实在是踩不过来。下面介绍一下本人使用的方法。
需要加缓存的页面(一般为列表页)
beforeRouteLeave (to, from, next) {
// ...
if (to.name === '详情页名字') {
//去往详情页时需要缓存
let obj = JSON.parse(JSON.stringify(this.$data))
obj['$name'] = this.$route.name
this.$store.commit('cache/updateCache', obj)
} else {
//否则清空缓存
this.$store.commit('cache/updateCache', {})
}
next()
},
created () {
let data = JSON.parse(JSON.stringify(this.$store.state.cache.cache))
if (data && data.$name && data.$name === this.$route.name) {
//有缓存赋值
for (let k in data) {
this[k] = data[k]
}
} else {
//无缓存初始化页面
this.init();
}
},
详情或编辑页
beforeRouteLeave (to, from, next) {
// 返回的不是列表页,清空缓存
if(to.name != '列表页名字'){
this.$store.commit('cache/updateCache',{})
}
next()
},
router全局拦截
router.beforeEach((to, from, next) => {
// 刷新页面时,清除缓存
if(!from.name){
store.commit('cache/updateCache', {})
}
window.scrollTo(0, 0)
next()
})