How to dynamically render images in Nuxt3

How do I dynamically render images in Nuxt 3? I want to do something like this:
<img src=`/assets/icons/${imageName}.svg`>
<img src=`/assets/icons/${imageName}.svg`>
4 Replies
Sagar Kapoor
Sagar Kapoor3mo ago
But the src property is not working as I had hoped it would. Nuxt is not able to find the image for some reason. Is it because it uses Vite?
Cue
Cue3mo ago
/assets/icons translates to public/assets/icons in your workspace. Are you sure that path exists?
Sagar Kapoor
Sagar Kapoor3mo ago
So, how should I render the images in the assets folder? I am able to render it like this <img src="~/assets/icons/customers.svg" :alt="item.title" /> But not when I want to render it dynamically
Cue
Cue3mo ago
Personally, if the assets do not change (which icons very rarely do) I would suggest moving them to the public directory. It is far more performant to load them from there. Loading assets dynamically is a limitation of vite. That said, you can scan the assets directory at runtime using a composable. For example:
export function useAssetIcon(path: string): string {
const assets = import.meta.glob('~/assets/icons/*', {
eager: true,
import: 'default',
})
// @ts-expect-error: wrong type info
return assets['/assets/icons/' + path]
}
export function useAssetIcon(path: string): string {
const assets = import.meta.glob('~/assets/icons/*', {
eager: true,
import: 'default',
})
// @ts-expect-error: wrong type info
return assets['/assets/icons/' + path]
}
And use it as such:
const imageSrc = useAssetIcon(imageName)
const imageSrc = useAssetIcon(imageName)
Want results from more Discord servers?
Add your server