uni-app选择性清除缓存

场景
uniapp的API清除缓存会删除所有缓存,包含登录时获取到的token信息,致使清除缓存后部分功能不可用

效果
在这里插入图片描述
在这里插入图片描述
实现

<!-- 功能列表 -->
<view class="menu-list">
	<view class="menu-item flex flex-align-center flex-justify-between" v-for="(item, index) in menuList" :key="index" @tap="handleSetting(item.name)">
		<view class="menu-left flex flex-align-center">
			<i class="iconfont" :class="item.icon" style="font-size: 10.25rpx;color: #333333;margin-right: 7.32rpx;"></i>
			<text>{{item.name}}</text>
		</view>
		<view class="menu-right flex flex-align-center">
			<text class="version" v-if="item.name === '当前版本'">v1.0.0</text>
			<text class="version" v-if="item.name === '清除缓存'">{{ cacheSize }} (可清除)</text>
			<i class="iconfont icon-jiantou2" style="font-size: 14.65rpx;color: #333333;"></i>
		</view>
	</view>
</view>
data() {
	return {
		menuList: [
			{
				name: '修改密码',
				icon: 'icon-mima'
			},
			{
				name: '清除缓存',
				icon: 'icon-qingchu'
			},
			{
				name: '当前版本',
				icon: 'icon-banbenxinxifuxy20160326'
			}
		],
		cacheSize: '0KB' // 缓存大小
	}
},
onLoad(){
	this.getCacheSize()
},
methods: {
	handleSetting(name){
		if(name === '清除缓存'){
			this.clearCache();
		}
		if(name === '修改密码'){
			//...
		}
	},
	// 获取缓存大小
	getCacheSize() {
		try {
			const storageInfo = uni.getStorageInfoSync();
			const currentSize = storageInfo.currentSize;
			
			// 计算登录相关数据的大小(用于显示非登录数据的缓存大小)
			const loginDataSize = this.calculateLoginDataSize();
			const nonLoginDataSize = Math.max(0, currentSize - loginDataSize);
			
			this.cacheSize = this.formatFileSize(nonLoginDataSize);
		} catch (error) {
			console.error('获取缓存大小失败:', error);
			this.cacheSize = '0KB';
		}
	},
	// 计算登录相关数据的大小
	calculateLoginDataSize() {
		let loginDataSize = 0;
		try {
			const token = uni.getStorageSync('Admin-Token');
			const username = uni.getStorageSync('username');
			const password = uni.getStorageSync('password');
			const rememberMe = uni.getStorageSync('rememberMe');
			
			if (token) loginDataSize += JSON.stringify(token).length * 2; // 估算大小
			if (username) loginDataSize += JSON.stringify(username).length * 2;
			if (password) loginDataSize += JSON.stringify(password).length * 2;
			if (rememberMe) loginDataSize += JSON.stringify(rememberMe).length * 2;
		} catch (error) {
			console.error('计算登录数据大小失败:', error);
		}
		return loginDataSize;
	},
	// 格式化文件大小
	formatFileSize(bytes) {
		if (bytes === 0) return '0KB';
		const k = 1024;
		const sizes = ['B', 'KB', 'MB', 'GB'];
		const i = Math.floor(Math.log(bytes) / Math.log(k));
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + sizes[i];
	},
	handleSetting(name){
		if(name === '清除缓存'){
			this.clearCache();
		}
		if(name === '修改密码'){
			uni.showToast({
				title: '用户暂不支持修改密码',
				icon: 'success'
			});
		}
	},
	// 清除缓存
	clearCache() {
		uni.showActionSheet({
			itemList: ['清除应用缓存(保留登录状态)', '清除所有数据(需要重新登录)'],
			success: (res) => {
				if (res.tapIndex === 0) {
					// 选择性清除缓存,保留登录相关数据
					this.clearCacheSelective();
				} else if (res.tapIndex === 1) {
					// 清除所有数据,包括登录信息
					this.clearAllData();
				}
			}
		});
	},
	// 选择性清除缓存(保留登录状态)
	clearCacheSelective() {
		uni.showModal({
			title: '清除应用缓存',
			content: `确定要清除应用缓存吗?\n当前缓存大小:${this.cacheSize}\n\n注意:将保留您的登录状态`,
			success: (res) => {
				if (res.confirm) {
					try {
						// 获取需要保留的登录相关数据
						const token = uni.getStorageSync('Admin-Token');
						const username = uni.getStorageSync('username');
						const password = uni.getStorageSync('password');
						const rememberMe = uni.getStorageSync('rememberMe');
						
						// 清除所有存储
						uni.clearStorageSync();
						
						// 恢复登录相关数据
						if (token) uni.setStorageSync('Admin-Token', token);
						if (username) uni.setStorageSync('username', username);
						if (password) uni.setStorageSync('password', password);
						if (rememberMe) uni.setStorageSync('rememberMe', rememberMe);
						
						// 更新缓存大小显示
						this.getCacheSize();
						
						uni.showToast({
							title: '缓存清除成功',
							icon: 'success',
							duration: 2000
						});
					} catch (error) {
						console.error('清除缓存失败:', error);
						uni.showToast({
							title: '清除缓存失败',
							icon: 'error',
							duration: 2000
						});
					}
				}
			}
		});
	},
	// 清除所有数据(包括登录信息)
	clearAllData() {
		uni.showModal({
			title: '清除所有数据',
			content: `确定要清除所有数据吗?\n当前缓存大小:${this.cacheSize}\n\n注意:清除后需要重新登录`,
			success: (res) => {
				if (res.confirm) {
					try {
						uni.clearStorageSync();
						this.cacheSize = '0KB';
						uni.showToast({
							title: '数据清除成功',
							icon: 'success',
							duration: 2000
						});
						// 延迟跳转到登录页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}, 2000);
					} catch (error) {
						console.error('清除数据失败:', error);
						uni.showToast({
							title: '清除数据失败',
							icon: 'error',
							duration: 2000
						});
					}
				}
			}
		});
	},
}
.menu-list {
	width: 100%;
	background: #FFFFFF;
	border-radius: 8.79rpx;
	margin-bottom: 14.65rpx;
	
	.menu-item {
		height: 58.6rpx;
		padding: 0 14.65rpx;
		border-bottom: 0.73rpx solid #EBEBEB;
		
		&:last-child {
			border-bottom: none;
		}
		
		.menu-left {
			text {
				font-family: 'PingFang SC';
				font-weight: 400;
				font-size: 10.25rpx;
				color: #333333;
			}
		}
		
		.menu-right {
			.version {
				font-family: 'PingFang SC';
				font-weight: 400;
				font-size: 8.79rpx;
				color: #333333;
				margin-right: 7.32rpx;
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值