1

Relevant codepen

I'm trying to generate dynamic image paths, but I'm missing something. For one reason or another, the method isn't executing on the src attribute in the img tags.

Here is the 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>

And here is the relevant 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']
    }
  }
})

I also did try binding the src to the img tag like :

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

But that causes nothing to render at all. Is it better here to use a method or computed properties in an instance like this?

Modermo
  • 1,852
  • 2
  • 25
  • 46
  • Where have you defined the getImageUrl method? – Tom Sep 30 '17 at 01:16
  • 1
    Using a method should work well. Try referring to this answer: https://stackoverflow.com/questions/40491506/vue-js-dynamic-images-not-working – Tom Sep 30 '17 at 01:23

1 Answers1

3

Try this out in the html:

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

When I change that in your pen, I see a failed request to this URL, and similar for the other fruits:

Request URL:https://codepen.io/boomerang/iFrameKey-9b0f86ca-8c55-3b83-2d9c-3367ada2ac69/assets/images/apple.jpg

Are there images for those fruits where you expect them to be? I changed the imgName method to the following and the image for the apple loads inside the pen:

imgName: function(fruit){
  if (fruit === 'apple') {
    return 'https://bestapples.com/wp-content/uploads/2015/10/apple-varieties.jpg'
  } else {
    var imgPath = 'assets/images/' + fruit + '.jpg';
    return imgPath;        
  }

}
clk
  • 238
  • 3
  • 9
  • Hey, yeah the images aren't meant to actually render in the pen. I just needed to figure out how to generate the image path. This works, so thanks :) – Modermo Sep 30 '17 at 01:39