vue实现图片缓存
使用Service Worker缓存图片
在Vue项目中注册Service Worker,通过Workbox库实现图片缓存策略。在vue.config.js中配置PWA插件:
module.exports = {
pwa: {
workboxOptions: {
runtimeCaching: [
{
urlPattern: /\.(?:png|jpg|jpeg|svg|gif)$/,
handler: 'CacheFirst',
options: {
cacheName: 'image-cache',
expiration: {
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60
}
}
}
]
}
}
}
本地存储实现缓存
使用浏览器的localStorage或IndexedDB存储图片数据。通过Canvas将图片转换为Base64格式:
function cacheImage(url) {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = new Image()
img.onload = () => {
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0)
const dataURL = canvas.toDataURL('image/jpeg')
localStorage.setItem(url, dataURL)
}
img.src = url
}
内存缓存策略
在Vue组件中使用响应式数据存储已加载的图片:
export default {
data() {
return {
imageCache: new Map()
}
},
methods: {
loadImage(url) {
if (this.imageCache.has(url)) {
return Promise.resolve(this.imageCache.get(url))
}
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
this.imageCache.set(url, img)
resolve(img)
}
img.src = url
})
}
}
}
浏览器原生Cache API
通过Fetch API和Cache接口实现图片缓存:
async function cacheImage(url) {
const cache = await caches.open('image-cache-v1')
const response = await fetch(url)
await cache.put(url, response.clone())
}
async function getCachedImage(url) {
const cache = await caches.open('image-cache-v1')
const response = await cache.match(url)
return response ? response.blob() : null
}
第三方库实现
使用lru-cache等库实现LRU缓存策略:

import LRU from 'lru-cache'
const imageCache = new LRU({
max: 100,
maxAge: 1000 * 60 * 60
})
function getImage(url) {
if (imageCache.has(url)) {
return imageCache.get(url)
}
return fetch(url)
.then(res => res.blob())
.then(blob => {
imageCache.set(url, blob)
return blob
})
}






