安装依赖
安装 store2
来替代传统 localstorage
包地址
https://www.npmjs.com/package/store2
npm i store2
简单使用
store.set(key, data[, overwrite]); // === store(key, data);
store.setAll(data[, overwrite]); // === store({key: data, key2: data});
store.get(key[, alt]); // === store(key);
store.getAll([fillObj]); // === store();
store.transact(key, fn[, alt]); // === store(key, fn[, alt]);
store.clear(); // === store(false);
store.has(key); // returns true or false
store.remove(key[, alt]); // removes key and its data, then returns the data or alt, if none
store.each(fn[, fill]); // === store(fn); optional call arg will be 3rd fn arg (e.g. for gathering values)
store.add(key, data[, replacer]); // concats, merges, or adds new value into existing one
store.keys([fillList]); // returns array of keys
store.size(); // number of keys, not length of data
store.clearAll(); // clears *ALL* areas (but still namespace sensitive)
创建工具类目录
src
|- utils
|-imgUtil.ts
import store from 'store2'
export class ImgUtil {
// 存储所有图片 {'avatar.png': 'src/xxx/xxx/xx'}
private static imgObj: Record<string, string> = {}
// 加载 && 缓存图片
static init() {
ImgUtil.imgObj = store.get('imgList') || {}
if (ImgUtil.isEmpty(ImgUtil.imgObj)) {
ImgUtil.load()
store.set('imgList', ImgUtil.imgObj)
}
}
// 获取图片
static getImage(imgName: string) {
return ImgUtil.imgObj[imgName]
}
// 一次性加载所有图片到内存
private static load() {
// 加载所有图片到内存
let imgMap = import.meta.glob('../assets/img/**/*.png', { eager: true, as: 'url' })
let absolutePath: string = ''
let imgName: string = ''
for (let path in imgMap) {
imgName = path.substring(path.lastIndexOf('/') + 1)
absolutePath = imgMap[path]
ImgUtil.imgObj[imgName] = absolutePath
}
}
private static isEmpty<T extends Record<string, string>>(obj: T) {
return !Object.getOwnPropertyNames(obj).length
}
}
export default ImgUtil.getImage
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { ImgUtil } from './utils/imgUtil'
// 加载所有图片到内存 && 缓存
ImgUtil.init()
const app = createApp(App)
app.mount('#app')
组件内使用
<template>
<div>
<img :src="getImg('阳光大男孩.png')" alt="" />
</div>
</template>
<script lang="ts" setup>
import getImg from './utils/imgUtil'
</script>