在小程序中,图片组件本身不直接支持全局缓存,但可以结合使用 wx.getStorage 和 wx.setStorage 来实现。以下是示例代码:
// index.js Page({ data: { imageUrl: '' }, onLoad: function () { const that = this; wx.getStorage({ key: 'cachedImage', success: function (res) { // 如果缓存存在 that.setData({ imageUrl: res.data }); }, fail: function () { // 如果缓存不存在,下载并缓存 const url = 'https://example.com/image.jpg'; // 替换为实际图片URL wx.downloadFile({ url: url, success: function (res) { if (res.statusCode === 200) { const tempFilePath = res.tempFilePath; that.setData({ imageUrl: tempFilePath }); // 缓存图片 wx.setStorage({ key: 'cachedImage', data: tempFilePath, }); } } }); } }); } });
然后在 WXML 中使用图片组件:
<!-- index.wxml --> <image src="{{imageUrl}}" mode="aspectFit" />
这样,当页面加载时,会先检查缓存,再决定是使用缓存的图片还是下载新图片。需要进一步的帮助吗?
网友回复