0

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.

1 Answer 1

1

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') } ] 
Sign up to request clarification or add additional context in comments.

3 Comments

It didin't work becuse I think i need to install a module to use that globEager. But from the part of the path give me a hint to use :src=require(@/assets/img/${item.img}) and them it worked!! Thank you!
thanks for your feedback. i forgot to tell you my env is vue3+vite. i guess your env is vue3+webpack, so globEager did not work. next time i will be more careful.
Oh sure! I have to study more about configs, but I will look for vite. I'm using the basic preset of vue cli. Thanks Yang! You help so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.