【问题标题】:v-bind image src with a computed property in Vue.JS在 Vue.JS 中使用计算属性 v-bind 图像 src
【发布时间】:2021-03-05 09:12:25
【问题描述】:

我有一个包含一些对象的 JSON 文件,这些对象正在使用计算属性呈现出来

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

所有数据都被无错误地渲染出来。

脚本标签:

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

模板标签:

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

但由于某种原因我无法渲染图像,我确信图像的路径是正确的。

【问题讨论】:

  • 你能解决这个问题吗?
  • 对不起,我是新手。什么是小提琴?
  • 没问题,如果你能用这样的小提琴重现你的问题:jsfiddle.net/boilerplate/vue 那么它会让我们更容易调试和帮助你。 :)
  • 这里是 jsfiddle 链接。唯一的区别是,在我的项目中,我的练习数据位于外部 JSON 文件中,而不是脚本标记本身中。 jsfiddle.net/zu548Lky

标签: javascript vue.js vuejs2


【解决方案1】:

最后我使用了以下方法:

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

并像这样输出图像

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

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 2019-02-08
    • 2018-01-09
    • 2019-03-13
    • 2018-05-15
    • 2019-01-03
    • 2019-06-21
    • 2018-11-23
    • 2017-08-26
    相关资源
    最近更新 更多