import goodStorage from 'good-storage'
export class LmgUtil{
static imgList:Record<string,string> = {}
static async storageLmgList(){
console.log(this.imgList) //这里打印this.imgList不论是第一次加载还是后续刷新是个空对象
this.imgList = goodStorage.get('imgList') || {}
console.log(this.imgList) //在这里打印this.imgList,第一次加载this.imgList就是有内容的
//不太理解的就是第二个log打印为什么第一次加载就会有内容,而第一个log打印不论什么时候都是空对象
if(this.isEmpty()){
await this.loadAllLmg()
goodStorage.set('imgList',this.imgList)
}
}
static isEmpty(){
//这里的this.imgList是有内容的,为什么getOwnPropertyNames(this.imgList)结果是空数组
return !Object.getOwnPropertyNames(this.imgList).length
}
//获取图片名称
static getImg(imgName:string){
return this.imgList[imgName]
}
static async loadAllLmg(){
const imgMap = import.meta.glob(
'../assets/img/**/*.png'
)
let absolutePath:string = ''
let imgName:string = ''
for(let relatviepath in imgMap){
const res:any = await imgMap[relatviepath]()
absolutePath = res.default
imgName = absolutePath.substring(absolutePath.lastIndexOf('/')+1)
this.imgList[imgName] = absolutePath
}
return this.imgList
}
}
第一个问题 因为代码顺序执行,所以不论是第一次加载还是后续刷新加载到第一次打印的位置,都会是空的,在不刷新的情况下,重新打印,才不会为空
第二个问题 因为Object.getOwnPropertyNames(this.imgList).length 返回数组的length ,而你前边有个!,所以会返回false,应该把!
去掉
!Object.getOwnPropertyNames([]).length 无论如何都是false
不知道你这个问题是否已经解决, 如果还没有解决的话:// localStorage和sessionStorage都有这些方法
// 1. setItem 存
localStorage.setItem('name', 'coder')
localStorage.setItem('age', 18)
// 2. length
console.log(localStorage.length);
// 3. key方法
console.log(localStorage.key(0));
// 4. getItem
console.log(localStorage.getItem('age'));
// 5. removeItem 移除某一个
console.log(localStorage.removeItem('age'));
// 6. clear 清空所有
console.log(localStorage.clear());