【uniapp 获取缓存及清除缓存】

小程序及H5

获取缓存:
使用uniapp中的wx.getStorageInfoSync()方法可以获取当前小程序或H5应用的本地缓存信息,如下所示:

let storageInfo = uni.getStorageInfoSync()
console.log(storageInfo)

其中,storageInfo是一个对象,包含以下属性:

  • keys:Array,存储当前缓存中所有的key(即缓存的键值对中的key);
  • currentSize:Number,当前缓存数据的大小,单位为KB;
  • limitSize:Number,当前缓存允许的最大数据大小,单位为KB。

清除缓存:
使用uniapp中的wx.clearStorageSync()方法可以清除当前小程序或H5应用的本地缓存,如下所示:

uni.clearStorageSync()

注意:

  • 这个方法将清除所有的本地缓存,因此请谨慎使用;
  • 如果只想清除特定的缓存,可以使用wx.removeStorageSync()方法来移除指定的缓存。

APP

获取缓存:

// 获取缓存
			getAppInfo() {
				// #ifdef APP-PLUS
				let self = this;
				plus.cache.calculate(size => {
					if (size < 1024) {
						self.cacheSize = size + 'B';
					} else if (size / 1024 >= 1 && size / 1024 / 1024 < 1) {
						self.cacheSize = Math.floor((size / 1024) * 100) / 100 + 'KB';
					} else if (size / 1024 / 1024 >= 1) {
						self.cacheSize = Math.floor((size / 1024 / 1024) * 100) / 100 + 'M';
					}
				});
				// #endif
			},

清除缓存:

//清除缓存
			clearCache() {
				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;
					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.getAppInfo(); // 重新计算缓存
								}, function(e) {
									console.log(e.message)
								});
							} else {
								entry.remove();
							}
						}, function(e) {
							console.log('文件路径读取失败')
						});
					}
					uni.showToast({
						title: '缓存清理完成',
						duration: 2000
					});

				} else { // ios  
					plus.cache.clear(function() {
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						that.getAppInfo();
					});
				}
			},

你可能感兴趣的:(uniapp,微信小程序,uni-app,缓存)