在Vue.js中生成动态img路径

时间:2017-09-30 01:11:25

标签: javascript vue.js

Relevant codepen

我试图生成动态图片路径,但我遗漏了一些东西。出于这样或那样的原因,该方法不会在src标记的img属性上执行。

这是HTML:

<div id="app">

  <component v-bind:fruits="fruits" is="fruits-list"></component>

</div>

<template id="fruits-template">
  <div>
    <ul>
      <li v-for="fruit in fruits">
        {{ fruit }}
        <img src="imgName(fruit)" />
      </li>
    </ul>
  </div>
</template>

这是相关的JS:

Vue.component('fruits-list', {
  template:'#fruits-template',
  props: ['fruits'],
  methods: {
    imgName: function(fruit){
      var imgPath = 'assets/images/' + fruit + '.jpg';
      return imgPath;
    }
  }
})

new Vue({
  el: '#app',
  data() {
    return {
      fruits: ['apple','pear','strawberry', 'peach']
    }
  }
})

我也尝试将src绑定到img标记,如:

<img :src="getImageUrl(fruit)" />

但这根本无法呈现。在这样的实例中使用方法或计算属性是否更好?

1 个答案:

答案 0 :(得分:3)

在html中试试这个:

INSERT INTO table2(table2.user_id) SELECT table1.id WHERE table1.username = "John";

当我在你的笔中更改它时,我看到对此URL的请求失败,并且与其他成果类似:

<img v-bind:src=imgName(fruit) />

那些水果的图像是否符合您的期望?我将Request URL:https://codepen.io/boomerang/iFrameKey-9b0f86ca-8c55-3b83-2d9c-3367ada2ac69/assets/images/apple.jpg方法更改为以下内容,苹果图像加载到笔中:

imgName