La primera forma (adecuada para manejar archivos de recursos de un solo enlace)
import homeIcon from '@/assets/images/home/home_icon.png'
<img :src="homeIcon" />
La segunda forma ----- la imagen está en el directorio src
Dirección de referencia de introducción de recursos estáticos del sitio web oficial de vite
new URL() + import.meta.url
const getAssetsFile = (url) => {
return new URL(`../assets/images/${
url}`, import.meta.url).href
}
Nota: Aquí solo puede obtener la ruta a través de …/…/, no a través de @/assets
La tercera forma: la imagen está en el directorio público.
/**
* @description: 动态加载图片 (注意:将图片放到public目录下)
* @param {*} imgUrl public目录下图片的地址:eg: /public/imgs/a.png, 则imgUrl为 ./imgs/a.png
* @return {*} 返回图片的绝对路径
*/
const loadPicture = (imgUrl) => {
let pathnameArr = location.pathname.split("/");
let realPathArr = []
pathnameArr.forEach(item =>{
if( item && item.slice(-5) !== '.html'){
realPathArr.push(item)
}
})
let realPath = location.origin + "/"
if(realPathArr.length > 0){
realPath = realPath + realPathArr.join('/') + "/"
}
return new URL(imgUrl, realPath).href;
}