使用keep alive 做翻页缓存
时间: 2023-07-20 13:16:21 浏览: 151
在Vue中,可以使用`<keep-alive>`组件来缓存组件的状态,从而实现翻页缓存的效果。具体的实现步骤如下:
1. 在需要缓存的组件外层添加`<keep-alive>`标签。
2. 在需要缓存的组件中添加`<keep-alive>`的子组件,可以通过`include`属性来指定需要缓存的组件名称,也可以通过`exclude`属性来指定不需要缓存的组件名称。
3. 在需要缓存的组件中添加`activated`和`deactivated`生命周期钩子函数,分别用于激活和失活时的处理逻辑。
例如,我们可以在一个包含两个页面的Vue应用中使用`<keep-alive>`来实现翻页缓存的效果,具体代码如下:
```html
<template>
<div>
<button @click="currentPage = 1">Page 1</button>
<button @click="currentPage = 2">Page 2</button>
<keep-alive>
<component :is="'Page' + currentPage" :key="currentPage"></component>
</keep-alive>
</div>
</template>
<script>
import Page1 from './Page1.vue'
import Page2 from './Page2.vue'
export default {
components: {
Page1,
Page2
},
data() {
return {
currentPage: 1
}
}
}
</script>
```
在上面的代码中,我们使用`<keep-alive>`来包裹`<component>`组件,用于缓存当前页面的状态。在`<component>`组件中,我们使用`:is`属性来动态绑定页面的组件名称,同时使用`:key`属性来指定页面的唯一标识符,以便Vue能够正确地缓存和更新页面状态。在`Page1`和`Page2`组件中,我们分别添加了`activated`和`deactivated`生命周期钩子函数,用于处理页面激活和失活时的逻辑。
阅读全文
相关推荐


















