一. 需求
对第一次请求回来的网络图片进行缓存,后续使用缓存的图片,而不用再次进行网络请求。
二. 实现
css:
img{
width: 100px;
height: 100px;
}
html:
<div id="container">
<img :src="this.saveImg(imgUrl)" >
</div>
js:
let vm = new Vue({
el:'#container',
data:{ // 模拟接口请求回来的网络图片地址
imgUrl :'https://img0.baidu.com/it/u=1477800726,2326569738&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
},
methods:{
// 对图片进行缓存的方法
saveImg(imgUrl){
let url = localStorage.getItem(imgUrl);
if(url){
console.log('使用了本地缓存的图片...')
return url;
}else{
console.log('未缓存图片,延迟下载并缓存...')
setTimeout(function(){