Reputation: 5
I'm trying to load the images in the assets/img folder in my vue3 project using a v-for inside a div, but they are not loading, just display my alt.
So, I have a vue component what will display a title and a paragraph and also a image. The images are in the assets/img folder, I'm getting the path of the image with a store that I created. When I try to just put the path of the image like this: src="../assets/img/img2.jpg"
the images renders.
Here is 1 of my state in the store.js:
content: [
{
headline: 'Teste',
paragraph: 'this is a paragraph',
img: '@/assets/img/img.jpg'
},]
Here is my template using the v-for:
<template>
<div>
<div
class="slider"
v-for="item, i in content"
:key='i'
>
<h1>{{item.headline}}</h1>
<p>{{item.paragraph}}</p>
<img
:src="item.img"
alt="test"
/>
</div>
</div>
</template>
My setup:
setup () {
const store = useStore()
const content = store.getters.getContent
return { content }
}
I tryed to use :src="require(item.img)"
but i got a webpack error by doing this:
Uncaught Error: Cannot find module '@/assets/img/img.jpg' webpackEmptyContext components sync:2
Also tryed to point the folder of the images in the src, :src="@/assets/img + item.img", but it didn't work.
Upvotes: 0
Views: 1711
Reputation: 259
I met this question before. Maybe the following code could help you.
// create a function in util.js
export const getSrc = ( name ) => {
const path = `/src/assets/img/${name}`
const modules = import.meta.globEager('/src/assets/img/*.jpg')
return modules[path].default
}
// use getSrc in someItem.vue
import { getSrc } from '@/util/util.js'
content: [
{
headline: 'Teste',
paragraph: 'this is a paragraph',
img: getSrc('img.jpg')
}
]
Upvotes: 1