- 1. Public folder
- 2. Import files individually
- 3. Import images with import.meta.url
- 4. Using dynamic images from an API
- 5. Dynamic inline background images
You’ve basically got 3 different ways to do it. Put images in the public folder and reference them normally (just a forward slash and the image name). Import images directly into your view/project and use them in your template. Use the native ESM
import.meta.url to assign images to variables, or create a function to use multiple images more easily. I’ll follow up at the end about referencing images from an API.
The simplest solution is to put your assets into the public folder, and then reference them as you normally would.
// add circle.svg to the public directory
You can import each image you need as a variable that can then be referenced where you need it. The obvious drawback to this is if you have multiple images.
More on this from the Vite docs here.
- Similar to example #2, you assign your image path to a constant and then use it in your template. Be aware you have to write out the entire path to the file i.e.
- Dynamically import images using a function and template literals
I’ve found this to be the most useful approach, especially with multiple images.
Be aware, in the Vite docs, the
./dir/ part of the path is a placeholder — update it to the path and folder of your project.
// from the docs
- You can also define a second parameter in the function so the image extension can be dynamic as well i.e.
Using images from an API doesn’t require any special treatment outside of normal data rendering in Vue. Just make your API request, get your data, and render it in the template.
I’ll add a little extra section here to quickly run over using dynamic background images with inline style tags. I’ll use the same function approach as in example #3.3, but use it inline.
Using images with Vite and Vue seemed like a head scratcher initially. I still don’t fully understand why it’s so counterintuitive when referencing local and/or dynamic assets. But hopefully this gives you a better idea. Again, I found the approach of using a function with dynamic file name and extension parameters to work best for multiple images with different formats. Be sure to check out the Vite docs for more info.