提交 6fbfa03d 作者: 方治民

feat: 优化 CacheImage 组件,增加调试参数和本地文件适配

上级 07c4f5dc
......@@ -26,53 +26,72 @@
type: String,
required: true,
},
debug: {
type: Boolean,
default: false,
},
})
const src = ref()
const hashCacheKey = ref()
onMounted(() => {
tryCache()
onMounted(async () => {
await tryCache()
})
// 监听 src 变化
watch(
() => props.src,
() => tryCache(),
async () => await tryCache(),
)
function log(...args: any[]) {
if (props.debug) {
console.log('[CacheImage]', ...args)
}
}
// 尝试缓存图片,如果失败则使用原始图片
async function tryCache() {
let url = props.src
if (!url) {
return
}
// #ifdef APP-PLUS
const hash = md5(url).toString()
hashCacheKey.value = `G_CACHE_IMAGE_${hash}`
if (uni.getStorageSync(hashCacheKey.value)) {
console.debug('CacheImage cache hit')
url = uni.getStorageSync(hashCacheKey.value)
} else {
console.debug('CacheImage cache miss')
try {
const res = await uni.downloadFile({ url })
if (res.statusCode === 200) {
const { savedFilePath } = await new Promise<UniApp.SaveFileSuccess>((resolve, reject) => {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (res) => resolve(res),
fail: (err) => reject(err),
// 如果是网络图片,则缓存到本地
if (url.startsWith('http')) {
// #ifdef APP-PLUS
const hash = md5(url).toString()
hashCacheKey.value = `G_CACHE_IMAGE_${hash}`
if (uni.getStorageSync(hashCacheKey.value)) {
log('cache hit', url)
url = uni.getStorageSync(hashCacheKey.value)
} else {
log('cache miss', url)
try {
const res = await uni.downloadFile({ url })
if (res.statusCode === 200) {
const { savedFilePath } = await new Promise<UniApp.SaveFileSuccess>((resolve, reject) => {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (res) => resolve(res),
fail: (err) => reject(err),
})
})
})
url = `${savedFilePath}`
url = `${savedFilePath}`
// 缓存图片本地地址
uni.setStorageSync(hashCacheKey.value, url)
// 缓存图片本地地址
uni.setStorageSync(hashCacheKey.value, url)
} else {
log('cache error', url, res)
url = props.src
}
} catch (e) {
console.error(e)
}
} catch (e) {
console.error(e)
}
log(props.src, '=>', url, hash, hashCacheKey.value)
// #endif
}
console.debug(props.src, '=>', url, hash, hashCacheKey.value)
// #endif
src.value = url
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论