带有 webpack require() 的 Vue.js 动态图像 src 不起作用 [英] Vue.js dynamic image src with webpack require() not working
问题描述
我正在尝试将图像 src 动态绑定到 ../assets/project_screens/image_name.jpg
形式的 URL.
I'm trying to bind image src dynamically to a URL of the form ../assets/project_screens/image_name.jpg
.
我的目录结构如下:
- src
-- assets
---- project_screens
-- profile
---- ProjectList.vue
-- store
---- profile.js
我知道我需要使用 webpack 的 require("path/to/image")
来帮助 webpack 构建这些图像,但是路径没有解析.
I know that I need to use webpack's require("path/to/image")
to help webpack build those images, but the path doesn't resolve.
// store/profile.js
projects = [
{
....
},
{
....
img_url: "../assets/project_screens/im1.jpg"
....
}
....
]
// profile/ProjectList.vue
<md-card
class="md-layout-item project-card"
v-for="(project, idx) in projects"
:key="idx"
>
<md-card-media>
<img :src="require(project.img_url)" alt="People" />
</md-card-media>
</md-card>
如果我使用 URL 字符串而不是动态传递 URL 字符串,它会起作用.环顾堆栈溢出,没有任何解决方案有帮助.我还缺什么吗?
If I used a URL string instead of dynamically passing the URL string it works. Looked around stack overflow and none of the solutions helped. Am I missing something else ?
推荐答案
我终于想通了!!如果文件名称完全以变量形式给出,则 Webpack 无法导入该文件,例如:
I finally figured it out!! Webpack cannot import the file if its name is completely given as a variable like:
require(imageUrl) // doesn't work
这是因为如果路径存储在变量中,它在编译时不知道路径.
This is because it doesn't know the path at compile time if the path is stored in a variable.
但是 Webpack 可以在 require() 中给定字符串插值时检测要捆绑的文件,例如:
But Webpack can detect files to bundle when it is given a string interpolation in require() like:
require(`../assets/profile_screens/${filename}`) // Works
这是可行的,因为 Webpack 在编译时知道路径../assets/profile_screens",因此它可以包含文件夹中的所有文件.
This works because Webpack knows the path "../assets/profile_screens" at compile time so it can include all the files inside the folder.
这篇关于带有 webpack require() 的 Vue.js 动态图像 src 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!