关于getImg中imgList始终为空对象
来源:3-5 通过图片名动态加载图片代码实现-3

幕布斯3267386
2022-09-06
开发环境,会出现两个一样的文件。debug的时候,getImg会走其中一个文件,获取list走另一个文件。所以getImg里面拿到的list全是空对象
1回答
-
keviny79
2022-09-06
不太明白同学为什么会出现两个 imgList.ts? 我讲的时候只有一个啊
这是vite3.x以上版本的更新代码:使用 import.meta.glob 取代 import.meta.globEager,npm run dev 和npm run preview 下都ok
import storage from 'good-storage'
export class LmgLoader {
static imgList: Record<string, any> = {}
static async getimgList() {
this.imgList = storage.get('imgList') || {}
if (!LmgLoader.imgList || !LmgLoader.isNotEmptyimgList()) {
this.imgList = LmgLoader.getImgAll()
storage.set('imgList', LmgLoader.imgList)
}
}
static isNotEmptyimgList() {
return Object.getOwnPropertyNames(LmgLoader.imgList).length
}
static getImg(name: string): string {
//console.log('name:', name)
// LmgLoader.imgList = LmgLoader.isNotEmptyimgList() ? LmgLoader.imgList : storage.get('imgList')
return LmgLoader.imgList[name] //
}
static getImgAll(): any {
const imgList: any = {}
const viewImgModules: Record<string, any> = import.meta.glob(`../assets/img/**/**/*.png`, { eager: true })
// import.meta.globEager(`../assets/img/**/**/*.png`)
for (const path in viewImgModules) {
if (viewImgModules[path].default) {
const pathName = path.substring(path.lastIndexOf('/') + 1)
imgList[pathName] = viewImgModules[path].default
}
}
storage.set('imgList', this.imgList)
return imgList
}
}
export default LmgLoader.getImg
012022-09-06
相似问题