Vue.js - 尝试绑定动态图像...我该怎么办? [英] Vue.js - Trying to bind dynamic images... what should I do?

查看:30
本文介绍了Vue.js - 尝试绑定动态图像...我该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Vue-CLI 3 和 Webpack 4 开始了一个新项目.一切正常,但由于某种原因我无法绑定图像.我的结构非常简单:

<div v-for="项目中的项目">{{ 项目名称 }}<img :src="'../public/images/' + item.img">

然后,我的 items 数组.它来自我在 Vuex 中的商店.

items = [{name: '我的名字-1',img: 'image-1.png'},{name: '我的名字-2',img: 'image-2.png'},{name: '我的名字-3',img: 'image-3.png'}]

我一直在玩 Webpack,因为我猜问题出在那里.我改变了一些配置,我用不同的路径(./,../,~/...)进行了测试,但没有任何效果......我做错了什么?提前致谢.

解决方案

要拥有动态图像路径,请使用 require():


<小时>

提示:在 require 参数中尽可能减少变化.因此,如果您知道所有图像的扩展名都是 .png,请执行以下操作:

当然,字符串 item 不应再有扩展名.

发生这种情况是因为 webpack 实际上解析了 require() 参数并将所有 可能 匹配它的文件包含在包中.你的参数越具体,webpack 包含在包中的永远不会使用的文件就越少.

I've started a new project using Vue-CLI 3 and Webpack 4. Everything works fine, but for some reason I'm not able to bind images. The structure that I have is so easy:

<div id="app">
   <div v-for="item in items">
      {{ item.name }}
      <img :src="'../public/images/' + item.img">
   </div>
</div>

And then, my items array. It comes from my Store in Vuex.

items = [
   {
      name: 'my-name-1',
      img: 'image-1.png'
   },
   {
      name: 'my-name-2',
      img: 'image-2.png'
   },
   {
      name: 'my-name-3',
      img: 'image-3.png'
   }
]

I've been playing with Webpack, because I guess the problem comes from there. I've changed some configurations, I've tested with diferents paths (./, ../, ~/...) but nothing works... What I'm doing wrong? Thanks in advance.

解决方案

To have dynamic image paths, use require():

<img :src="require('../public/images/' + item.img)">



Tip: leave the least variation possible in the require args. So if you know all images will have the extension .png, do:

<img :src="require('../public/images/' + item + '.png')">

Of course, the string item should not have the extension anymore.

This happens because webpack actually parses that require() argument and includes in the bundle all files that may match it. The more specific your arg is, the less files that will never be used will be included in the bundle by webpack.

这篇关于Vue.js - 尝试绑定动态图像...我该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆