SoFunction
Updated on 2025-04-05

3 ways to dynamically load images in Vue3 vite

The first method (suitable for processing resource files for single links)

import homeIcon from '@/assets/images/home/home_icon.png'
<img :src="homeIcon" />

The second method----- The picture is in the src directory

Reference address for static resource introduction of vite official website

new URL() +

const getAssetsFile = (url) => {
   return new URL(`../assets/images/${url}`, ).href
}

Note: The path can only be obtained through …/…/, this method, and cannot be obtained through @/assets

The third method---- The picture is in the public directory

/**
  * @description: Dynamically load pictures (note: put the pictures in the public directory)
  * @param {*} imgUrl The address of the image in the public directory: eg: /public/imgs/, then imgUrl is ./imgs/
  * @return {*} Return the absolute path to the image
  */
const loadPicture = (imgUrl) =&gt; {
	let pathnameArr = ("/");
	let realPathArr = []
	(item =&gt;{
		if( item &amp;&amp; (-5) !== '.html'){
			(item)
		}
	})
	let realPath =  + "/"
	if( &gt; 0){
		realPath = realPath + ('/') + "/"
	}

	return new URL(imgUrl, realPath).href;
}

Summarize

This is the article about 3 ways to dynamically load images in Vue3’s vite. For more relevant vite images dynamic loading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!