David D.
David D.

Reputation: 119

v-bind image src with a computed property in Vue.JS

I have a JSON file with some objects, which are getting rendered out using a computed property

JSON:

{
     "id": 6,
     "formula": "2+2",
     "description": "Just a description.",
     "image": "../assets/img/id6.png",
     "answers": [
        { "answerId": 0, "answerInput": "Funktion", "correct": false},
        { "answerId": 1, "answerInput": "Relation", "correct": true}
     ]
}

All data is getting rendered out with no errors.

script tag:

computed:{
  filterById(){
      return this.exercises.find(exercises => exercises.id === this.exId)
    }
  }

template tag:

<div class="task-description">
  <h2>{{ filterById.description }}</h2>
  <img :src="`${filterById.image}`" alt="">
</div>

but for some reason I can not render the image, I am sure the path to the image is correct.

Upvotes: 4

Views: 4745

Answers (1)

David D.
David D.

Reputation: 119

At the end I used the following method:

getImgUrl(path) {
    var images = require.context('../assets/img/')
    return images('./' + path + ".png")
}

and outputed the image like this

<img v-if="filterById.id == 7 || filterById.id == 6" :src="getImgUrl(filterById.image)">

Upvotes: 6

Related Questions