uniapp清除本地数据缓存的方法及详细步骤

1.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.data里面用currentSize表示本地缓存

data() {
		return {
			currentSize: '' 
		};
	},

3.在methods里面添加获取本地缓存大小的函数和清除本地缓存的函数

methods: {
			// 获取本地缓存大小
			getStorageSize() {
				let that = this;
				plus.cache.calculate(function(size) {
					let sizeCache = parseInt(size);
					if (sizeCache == 0) {
						that.currentSize = "0B";
					} else if (sizeCache < 1024) {
						that.currentSize = sizeCache + "B";
					} else if (sizeCache < 1048576) {
						that.currentSize = (sizeCache / 1024).toFixed(2) + "KB";
					} else if (sizeCache < 1073741824) {
						that.currentSize = (sizeCache / 1048576).toFixed(2) + "MB";
					} else {
						that.currentSize = (sizeCache / 1073741824).toFixed(2) + "GB";
					}
				});
			},
			// 清理缓存
			clearStorage() {
				let that = this;
				let os = plus.os.name;
				if (os == 'Android') {
					let main = plus.android.runtimeMainActivity();
					let sdRoot = main.getCacheDir();
					let files = plus.android.invoke(sdRoot, "listFiles");
					let len = files.length;
					console.log(files, len)
					for (let i = 0; i < len; i++) {
						let filePath = '' + files[i]; // 没有找到合适的方法获取路径,这样写可以转成文件路径  
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
							if (entry.isDirectory) {
								entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录
									that.files = []
									uni.showToast({
										title: '清除成功',
										duration: 2000
									});
									that.getStorageSize(); // 重新计算缓存  
								}, function(e) {
									console.log(e.message)
								});
							} else {
								entry.remove();
							}
						}, function(e) {
							console.log('文件路径读取失败')
						});
					}
				} else { // ios  
					plus.cache.clear(function() {
						uni.showToast({
							title: '清除成功',
							duration: 2000
						});
						that.getStorageSize();
					});
				}
			},
		},
**注意在onLoad里面执行下getStorageSize(),当页面进入之后就获取下本地缓存的大小**
onLoad() {
		this.getStorageSize()
	},
最后:点击清理缓存之后会重新获取本地缓存大小,并弹出清除成功的提示


文章也参考了https://blog.csdn.net/csl125/article/details/113261715 的方法,
在uniapp社区里面查看SeeMyEyes的文章也获得了一些灵感,
https://ask.dcloud.net.cn/article/36305
大家有问题可以在评论区交流。如有不足之处,也欢迎大家指正!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐