Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS interpolation in src attribute

In a VueJS with TypeScript and Vuetify app, I have ten pictures called picture1.png, picture2.png, picture3.png, etc. I'm trying to make <div><img src="../assets/pictures/picture1.png"/></div> for each of them. Here's my code:

<template>
    <div class="home">
        <div class="pictures">
            <div v-for="index in Array.from({length: 10}, (v, k) => k+1)" :key="index">
                <img src='../assets/pictures/picture{{index}}.png'>
            </div>
        </div>
    </div>
</template>

This has the error that interpolation in attributes has been removed. As explained to answer this question, you're supposed to use v-bind instead:

<template>
<div class="home">
    <div class="picture">
        <div v-for="index in Array.from({length: 10}, (v, k) => k+1)" :key="index">
            {{index}}
            <img :src="'../assets/pictures/picture' + index + '.png'">
        </div>
    </div>
</div>

That outputs ten broken images, as an example, with src literally like this: src="../assets/pictures/picture1.png"

And that file doesn't exist, so it shows the broken image icon.

If I just use <img src='../assets/pictures/picture1.png'>, it works, and the image url as shown in the dom inspector is <img src="/img/picture1.ea361a2e.png">.

Is there a way to properly handle building img srcs in Vue dynamically but still allow it to handle it the way it handles normal srcs without dynamic binding?

like image 444
Menasheh Avatar asked Jul 05 '26 02:07

Menasheh


1 Answers

I've had luck doing the following.

:src="require(`images/image-${index}.png`)"
like image 79
Johan Baaij Avatar answered Jul 06 '26 16:07

Johan Baaij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!