问题描述
我正在尝试将image 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.
但是,在require()中给字符串内插时,Webpack可以检测到要捆绑的文件,例如:
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无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!