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
img
<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>
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)" />
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;
}
}