uniapp页面缓存
时间: 2023-08-19 20:05:33 浏览: 73
在 Uniapp 中,可以通过设置页面的 `keepAlive` 属性来实现页面缓存。当 `keepAlive` 属性被设置为 `true` 时,页面在切换时将会被缓存,不会被销毁。
以下是一个示例代码:
```html
<template>
<view>
<text>这是一个缓存的页面</text>
</view>
</template>
<script>
export default {
keepAlive: true, // 设置页面缓存
}
</script>
```
在上面的示例中,页面被设置为缓存,当该页面被切换离开时,页面实例不会被销毁,下次再次进入该页面时,将会直接使用之前的实例,不会重新创建。
需要注意的是,只有在使用 `vue-router` 进行页面切换时,`keepAlive` 属性才会生效。如果使用其他方式进行页面切换,例如通过 `wx.navigateTo`、`navigateTo` 等方法,则页面不会被缓存。
另外,如果想要在某些情况下动态控制页面是否缓存,可以使用 `activated` 和 `deactivated` 生命周期函数,在这些生命周期函数中通过动态修改 `keepAlive` 属性来实现。
相关问题
uniapp 页面缓存
对于 UniApp,页面缓存是一种常用的性能优化技术。UniApp 默认开启了页面缓存,它会将页面的 DOM 结构及数据缓存起来,当再次打开该页面时,会直接使用缓存的内容,以提升页面打开速度和用户体验。
UniApp 的页面缓存有两种模式:页面级缓存和组件级缓存。
1. 页面级缓存:在 `pages.json` 配置文件中,可以通过设置 `page.json` 中的 `cache` 字段来控制页面的缓存行为。可选的值有:
- `default`:默认值,表示该页面会被缓存。
- `none`:表示该页面不被缓存,每次打开都会重新加载数据。
- `no-cache`:表示该页面会被缓存,但离开页面后会被销毁。
- `reconnect`:表示该页面会被缓存,并且在离开页面后再次进入时会触发 `onReconnect` 生命周期钩子函数。
2. 组件级缓存:组件级缓存是通过 `<keep-alive>` 标签来实现的。将需要缓存的组件包裹在 `<keep-alive>` 标签内,即可实现组件级的缓存。例如:
```html
<template>
<keep-alive>
<component-a></component-a>
</keep-alive>
</template>
```
使用页面缓存可以有效减少页面的渲染和数据请求时间,但需要注意的是,缓存的页面或组件可能会导致内存占用增加,对于一些占用较多内存的页面或组件,可以考虑通过手动销毁缓存来释放内存。
uniapp清理页面缓存
要清理uniapp页面缓存,可以按照以下步骤进行操作:
1. 在HTML部分,添加一个触发清理缓存操作的按钮:
```html
<view class="li" @click="clearStorage">清理缓存 <text class="current-size">{{currentSize}}</text> <uni-icons type="arrowright" size="18" color="#ddd" class="fr"></uni-icons></view>
```
2. 在script的js部分,定义清理缓存相关的方法和获取缓存大小的方法:
```javascript
data() {
return {
storageSize: '0M',
}
},
onLoad() {
this.getStorageSize() //获取缓存
},
methods: {
//获取app的缓存大小
getStorageSize: function () {
let that = this;
uni.getStorageInfo({
success(res) {
let size = res.currentSize;
if (size < 1024) {
that.storageSize = size + ' B';
} else if (size / 1024 >= 1 && size / 1024 / 1024 < 1) {
that.storageSize = Math.floor(size / 1024 * 100) / 100 + ' KB';
} else if (size / 1024 / 1024 >= 1) {
that.storageSize = Math.floor(size / 1024 / 1024 * 100) / 100 + ' M'; }
}
})
},
//删除缓存
clearStorage: function () {
let that = this;
uni.showModal({
title: '提示',
content: '确定清除缓存吗?',
confirmText: '立即清除',
success(res) {
if (res.confirm) {
uni.clearStorageSync();
that.getStorageSize(); //重新获取并显示清除后的缓存大小
uni.showToast({
title: '清除成功',
icon: 'none'
})
//清除完后跳到登录页面
setTimeout(() => {
uni.redirectTo({
url: '/pages/login/login',
animationType: 'pop-in',
animationDuration: 200
})
}, 1300)
}
}
})
},
}
```
3. 在组件里添加一个触发清理缓存的事件:
```html
<view class="row" @click="clearStorage">
<view class="title">清除缓存</view>
<view class="right">
<view class="tis tell">{{storageSize}}</view>
<uni-icons type="arrowright" color="#C9C9C9" size="20"></uni-icons>
</view>
</view>
```