liewife
liewife

Reputation: 51

how to attach image using v-for in vue 3

im trying to make a set of images using v-for loop, but somehow it doesn't recognise variables inside the tag. pic is broken and alt just shows me {{ item.alt }} thing. Here is my HTML:

<section class="our-technologies__section" v-for="(item, index) in tech_item" :key="index">
        <div class="technologies__logo" @click="activeIndex = index" :class="{active: activeIndex === index}">
            <img src="{{ item.src }}" alt="{{ item.alt }}">
            <p>{{item.title}}</p>
        </div>
</section>

And here are script:

export default {
    name: "OurTechnologies",
    data: function () {
        return{
            tech_item: [
                { title: 'Twilio', text: 'gfmds/lgkmlk/f', src: '../../images/twilio.png', alt: 'Twilio' },
                { title: 'Android', text: '12334356676', src: '../../images/android.png', alt: 'Android' },
            ],
            activeIndex: 0,
        } 
    },
}

I tried to use <img :src="item.src" :alt="item.alt"> and its still no results.

Upvotes: 1

Views: 1459

Answers (2)

Daniel
Daniel

Reputation: 35724

<img :src="item.src" :alt="item.alt"> should work ™, but then I don't know enough about the environment you have set up. I quickly tried with a fresh project using vite and using the App component (so that it was root level), it didn't even need require for it to work. For this to work your images would be usually be in the ./src/assets/ directory, which they are not and I'm wondering if that's what is causing the problems, that the images are falling out of scope. You likely have a different setup, but I think you might able to use another option.

Place the images into the ./public/images/ folder. This will make them included as part of the bundle whether you're using dev/serve or build. Then reference them as /images/*.png without require or import. As long as you are serving the app at root level so that /images resolves correctly this should make it work. Otherwise it may need a bit of extra finessing to target the right directory.

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

In vue cli you should use require to load the image :

<img :src="require(item.src)" :alt="item.alt"/>

Upvotes: 1

Related Questions