v-bind image src z obliczoną właściwością w Vue.JS

Nov 22 2020

Mam plik JSON z niektórymi obiektami, które są renderowane przy użyciu obliczonej właściwości

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}
     ]
}

Wszystkie dane są renderowane bez błędów.

tag skryptu:

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

tag szablonu:

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

ale z jakiegoś powodu nie mogę renderować obrazu, jestem pewien, że ścieżka do obrazu jest poprawna.

Odpowiedzi

2 DavidD. Nov 22 2020 at 15:33

Na koniec zastosowałem następującą metodę:

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

i wyświetlił obraz w ten sposób

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