方案1:
在获取数据后调用
this.getLocalPath(this.list, this.fixPath)
1.先遍历数据,看看本地有没有图片的静态文件
1 getLocalPath(list, callback) { 2 plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => { 3 fs.root.createReader().readEntries((entries) => { 4 let data = []; 5 for (var i = 0; i < entries.length; i++) { 6 data.push(entries[i].fullPath) 7 } 8 callback(data, list) 9 }) 10 }) 11 }
2.1.有数据则替换为本地路径
2.2 没有数据则返回个错误链接
fixPath(data, list) { list.forEach(item => { let arr = item.img.split('/') let filename = arr[arr.length - 1] let filePath = data.find(path => path.includes(filename)) item.img = filePath ? 'file://' + filePath : filename }) }
3.当图片错误的时候执行@error事件,事件内先拼接正确的链接随后下载图片
<image :src="item.img" mode="heightFix" @error="imageError(item)"></image>
imageError(item) { let httpUrl = 'https://xxx/' // 服务器地址 let url = httpUrl + item.img this.$set(item, 'img', url) // 下载到本地 plus.downloader.createDownload(url, {}, (d, status) => { status != 200 && console.log('error') console.log("Download success: " + d.filename); }).start() }
方案2:
不使用@error,性能不如方案1
其他代码一样,2.2如下
fixPath(data, list) { list.forEach(item => { if (item.type == 'image' || item.type == 'forwardimage') { let arr = item.payload.url.split('/') let filename = arr[arr.length - 1] let filePath = data.find(path => path.includes(filename)) // 如果在本地找到了,则读取本地路径,没有则下载到本地 if (filePath) { item.payload.url = 'file://' + filePath } else { plus.downloader.createDownload(item.payload.url, {}, (d, status) => { status != 200 && console.log('error') console.log("Download success: " + d.filename); }).start() } } }) }
h5+参考API https://www.html5plus.org/doc/zh_cn/io.html
浙公网安备 33010602011771号