Vue3+vite dynamically imports static resources (dynamically imports pictures in the assets folder)

// 在vue3中如果我们通过 require 引入图片会发现报错: require is not defind,因为require是webpack的方法.

<img :src="require('@/assets/images/icon.png')" />

It is relatively simple to import a single resource file, so I won't talk about it here.

Mainly explain import.meta and its specific use:

// 当我们多个地方需要用到图片时,我们可以把这些图片搞成一个数组

const imgList = ref([
    new URL('../assets/images/icon.png', import.meta.url).href,
    new URL('../assets/images/icon2.png', import.meta.url).href,
    new URL('../assets/images/icon3.png', import.meta.url).href,
])
// 使用
<img :src="imgList[0]" alt="图片">
<img :src="imgList[1]" alt="图片">
<img :src="imgList[2]" alt="图片">

// 获取当前模块或文件的路径
import.meta.url

// 将当前模块或文件的路径和图片路径拼接成一个完成的路径
new URL('../assets/images/icon.png', import.meta.url).href 

import.meta is mentioned in Ruan Yifeng's article

29. The latest proposal - import.meta - "Ruan Yifeng ECMAScript 6 (ES6) Standard Introduction Course Third Edition" - 书栈网· BookStack

Guess you like

Origin blog.csdn.net/m0_58293192/article/details/129299291