我正在尝试生成动态图像路径,但我遗漏了一些东西。由于某种原因,该方法未在 img
标记中的 src
属性上执行。
这是 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
绑定(bind)到 img
标签,例如:
<img :src="getImageUrl(fruit)" />
但这根本不会导致任何渲染。在这样的实例中使用方法或计算属性更好吗?
最佳答案
在 html 中试试这个:
<img v-bind:src=imgName(fruit) />
当我在你的笔中更改它时,我看到对该 URL 的请求失败,其他水果也类似:
请求网址:https://codepen.io/boomerang/iFrameKey-9b0f86ca-8c55-3b83-2d9c-3367ada2ac69/assets/images/apple.jpg
是否有您期望的水果图片?我将 imgName
方法更改为以下内容,并将苹果的图像加载到笔内:
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;
}
}
关于javascript - 在 Vue.js 中生成动态 img 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498626/