在v-for循环中无法通过v-bind显示图像
我知道关于如何在v-for中使用v-bind绑定到img src的问题和答案很多,但是,我花了一整天的时间徒劳地进行实验.我为一个重复的问题表示歉意,但是有人可以帮助我吗?
I know there are a lot of questions and answers about how to use v-bind in v-for to bind to img src ... however, I spent a whole day experimenting in vain. I apologize for a duplicate question, but could anyone help me?
我正在使用vue@2.6.12和@ vue/cli 4.5.6.我试图在v-for循环中显示多个图像,将文件路径绑定到img src.我在Skills.json中有技能数据,试图在Skills.vue中显示它们.下面的代码仅显示空白屏幕.
I am using vue@2.6.12 and @vue/cli 4.5.6. I am trying to show multiple images in v-for loop, binding file paths to img src. I have skills data in skills.json, trying to display them in Skills.vue. The code below just shows blank screen.
感谢您的帮助,谢谢.
skills.json
skills.json
[
{
"id": 1,
"name": "C#",
"logo": "C-Sharp.svg"
},
{
"id": 2,
"name": "Azure",
"logo": "azure.svg"
}
]
Skills.vue
Skills.vue
使用vue开发人员工具,我可以确认数据已正确导入到技能数组中(但未显示).
Looking at vue developer tool, I could confirm the data is correctly imported into skills array(but not showing up).
<template>
<div class="container">
<div class="items">
<div class="item" v-for="skill in skills" :key="skill.id">
<img :src="require(`${logoPath}${skill.logo}`)" />
</div>
</div>
</div>
</template>
<script>
import skillsJson from '../assets/skills.json';
export default {
data() {
return {
skills: skillsJson,
logoPath: '../assets/img/',
};
},
};
</script>
src文件夹结构
C:.
│ App.vue
│ main.js
├─assets
│ │ skills.json
│ ├─icons
│ ├─img
│ │ azure.svg
│ │ C-Sharp.svg
│ └─scss
├─components
├─router
│ index.js
└─views
Experience.vue
HelloWorld.vue
Home.vue
Skills.vue
您需要了解 require()
(或 import()
)是由Webpack在以下位置处理的建立时间.Webpack无法执行代码(在构建时),并且可能知道运行时的值.看看文档(这是关于 import()
但 require()
几乎相同)
You need to understand that require()
(or import()
) is handled by Webpack at build time. Webpack can't execute your code (at build time) and possibly know what the value at runtime will be. Take a look at the docs (it's about import()
but require()
is almost same)
简单的解决方法是仅使路径的一部分动态化,以便Webpack至少获得一些提示,提示应使哪个文件可用...
Simple fix would be to make only part of the path dynamic so Webpack gets at least some hint what file should be made available...
替换
<img :src="require(`${logoPath}${skill.logo}`)" />
作者
<img :src="require(`../assets/img/${skill.logo}`)" />
TLDR
Webpack的 require()
至少需要文件路径的某些部分是完全静态的!
Webpack's require()
needs at least some part of the file path to be completely static!