Search code examples
vuexvuejs3

Trying to load an image inside a assets/img folder in a v-for, but the images does not load


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.


Solution

  • 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')
       }
    ]