keep-alive如何设置跳转指定页面缓存,其它页面不缓存并清除之前的缓存?

页面跳转详情页然后返回页面是保持之前的状态没问题,跳转其它页面再返回当前页面是初始页面状态也没问题,但再进入详情再返回页面确是第一次的状态,这种情况怎么处理?

beforeRouteLeave(to, from, next) {

console.log('aaaaaaaaaaaaa', to)

//此处也可以加判断

if (to.name === 'customerAsset_detail' || to.name === 'unmatch') {

from.meta.keepAlive = true //需要缓存

to.meta.isBack = true

} else {

from.meta.keepAlive = false // 不需要缓存

to.meta.isBack = false

}

next()

},


回答:

换个方式完美实现

    mounted() {

const dataList = JSON.parse(localStorage.getItem('dataList')) //对象格式需要转换一下

const tags = JSON.parse(localStorage.getItem('tags')) //数组格式需要转换一下

const page = localStorage.getItem('page')

if (dataList || tags || page) { //如果有数据就按条件调用接口没有直接调用接口

this.form = dataList //form表单

this.tabIndex = tags

if (this.form.scopeDate) {

this.start_time = this.$moment(new Date(this.form.scopeDate[0])).format('YYYY-MM-DD')

this.end_time = this.$moment(new Date(this.form.scopeDate[1])).format('YYYY-MM-DD')

} else {

this.start_time = ''

this.end_time = ''

}

this.page = Number(page)

if (tags) {

this.addBao()

}

localStorage.removeItem('dataList') //用完及时清空

localStorage.removeItem('tag')

localStorage.removeItem('page')

if (this.page && this.page > 1) { // 定位table列表第几页的问题

this.getData(this.page)

} else {

this.getList()

}

} else {

this.getList()

}

this.labelCenter()

},

    beforeRouteLeave(to, from, next) {

if (to.path === '/statistics/particulars') { //跳转指定页面进行缓存

const dataList = JSON.stringify(this.form) //对象格式需要压缩存储

const tags = JSON.stringify(this.tabIndex) //数组格式需要压缩存储

localStorage.setItem('dataList', dataList)

localStorage.setItem('tags', tags)

localStorage.setItem('page', this.page)

}

next()

},


回答:

一般遇到的场景应该是这个页面是缓存的,只是在个别情况下希望这个页面的缓存失效(也就是我在离开页面前决定缓不缓存)。你代码这种写法是我在上一次离开这个页面的时候就要决定下一次缓不缓存


回答:

你这问题没描述明白,你用ABC(C代表详情页)三个页互相跳转来描述下问题
A->C C返回A A是原来的页面状态 没问题
A->B B 返回A A是原来的页面状态 也没问题
A->C C 现在展示的第一次的状态? 证明你C页面的写法不对啊,
1.C详情页不应该被keepAlive
2.或者你把获取详情信息 的操作绑定到 传入的id上当id 改变时 就获取详情,
3.或者放到 active 生命周期也去调用一遍详情更新。
个人倾向于1或者3 因为你更改信息后再次打开详情页 详情页 应该变更,正常应该每次打开都去更新信息,只有带表单 如带有查询表单或分页的table页 或者表单提交页 keepAlive才有意义 是为了保存上传的表单信息(分页信息也归类于其中),像详情这种单个的纯展示keppAlive没有意义


回答:

拿这个问题做个实验

以下是来自ChatGPT的回答:

你可以通过设置 HTTP 头来控制网页的缓存方式。如果你想指定某个页面被缓存,你可以在响应头中添加一个 Cache-Control 头,并设置其值为 public, max-age=<seconds>,其中 <seconds> 是缓存的时间长度(以秒为单位)。这样,浏览器就会在指定的时间内缓存这个页面。

如果你想清除之前缓存的内容,你可以在响应头中添加一个 Cache-Control 头,并设置其值为 no-cache, no-store, must-revalidate。这样,浏览器就会在访问这个页面时不使用缓存,并清除之前的缓存内容。

下面是一个例子,展示了如何设置 HTTP 头来控制缓存:

// 设置缓存

response.setHeader('Cache-Control', 'public, max-age=300'); // 缓存页面 300 秒

// 清除缓存

response.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');

请注意,上面的代码仅作为示例,并不能直接用于实际应用中。

希望这些信息对你有帮助。

以上是 keep-alive如何设置跳转指定页面缓存,其它页面不缓存并清除之前的缓存? 的全部内容, 来源链接: utcz.com/p/933366.html

回到顶部