Modermo Modermo - 3 years ago 186
Javascript Question

Generate dynamic img paths in Vue.js

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?

clk clk
Answer Source

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

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download