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

标签 javascript vue.js

Relevant codepen

我正在尝试生成动态图像路径,但我遗漏了一些东西。由于某种原因,该方法未在 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/

相关文章:

javascript - 编写 ExpressJS 应用程序时,为什么不使用 "new"关键字?

vue.js - 如何在Vue Js中加载静态图片

javascript - Vue Js 路由 - 没有路径的父级

file-upload - 在 ASP.NET Core 中使用 Axios 和 Vue.JS 进行多文件上传

javascript - 为什么我不能在我的组件中访问 Prop ?

javascript - 获取文件中的 TypeScript 类并读取其中的单个部分

javascript - 302响应错误

javascript - JavaScript 中区分 0 和空字符串的最安全方法是什么?

javascript - 函数外部数据为 null (Vue Js)

javascript - map 容器正在被另一个实例重用