Search code examples
vue.jsbootstrap-vue

How can I add a variable to an image link in a card (vue-bootsrap)?


I'm trying to add an id taken from an API to the end of an image url so that it's a different image for each card in the loop. I think img-src might exclusively accept a string though, and v-bind exclusively an attribute

        <b-card
            class="sCardCourse m-3"
            v-bind:header="course.title"
            v-for="course in courses"
            :key="course.id"
            overlay
            img-src="https://picsum.photos/500/300/?image=26"
            img-alt="Card Image"
            header-class="text-center headHeight"
        >
            <div class="sbtn">
                <b-button class="fbtn" :to="{ name: 'viewCourse', params: { id: course.id}}" variant="warning">View</b-button>
                <b-button :to="{ name: 'editCourse', params: { id: course.id}}" variant="warning">Edit</b-button>
            </div>
        </b-card>

I tried:

  • Adding it at the end with just a + (error saying + isn't accepted)

  • Adding {{course.id}} in place of the static number at the end of the url (error saying Interpolation inside attributes has been removed and to use v-bind or :id)

  • Using v-bind: on the img-src (error saying v-bind requires an attribute).

  • Adding {{v-bind:course.id}} at the end (same error as just {{course.id}})

Is it possible with the img-src property, or do I have to do it a different way?


Solution

  • Problem

    The issue here is that with the v-bind directive (abbreviated by the colon sign) the line in between those quotes is parsed as Javascript. This means that you need a different pair of quotes to represent a string and concatenate a variable to it.

    img-src="without v-bind this is just text" // OK
    :img-src="with v-bind this is javascript so it gives an error" // NOT OK
    :img-src="'with v-bind and single quotes this is a valid javascript string'" // OK
    

    Solution

    Using a template literal:

    :img-src="`https://picsum.photos/500/300/?image=${course.id}`"
    

    Using a string with concatenation:

    :img-src="'https://picsum.photos/500/300/?image=' + course.id"