I want to create 3 cards dynamically. Each card has an image and I want to set a path dynamically for each of them but I can't use the tilde ~
because the tilde does not convert to the absolute path:
<img
:src="'~/assets/images/how-to-use/image1.jpg'"
:alt="part.title"
/>
I'm getting this error :
GET http://localhost:3000/~/assets/images/how-to-use/image2.jpg 404 (Page not found: /~/assets/images/how-to-use/image1.jpg)
I set my buildAssetsDir
to example
but I can't even do this :
<img
:src="'example/assets/images/how-to-use/image1.jpg'"
:alt="part.title"
/>
this code won't work after build time. but why?
CodePudding user response:
I found this way:
<script>
const glob = import.meta.glob("~/assets/images/how-to-use/*", {
eager: true,
});
const getImageAbsolutePath = (imageName: string): string => {
return glob[`/assets/images/how-to-use/${imageName}`]["default"];
};
</script>
You can pass your imageName
(don't forget the extension) to this function and get the absolute path.
This way works even after the build.
You can't use the:
<img
:src="'example/assets/images/how-to-use/image1.jpg'"
:alt="part.title"
/>
but why?
It's because nuxt3 will change the assets file name too, so this path is not correct
important notes
require
does not work anymore in nuxt3- you can use
import image1Name from '../assets/images/how-to-use/image1.jpg'
and useimage1Name
in your template too. - you can always add your images to the public folder these ways work after the build