简体   繁体   English

带有 webpack require() 的 Vue.js 动态图像 src 不起作用

[英]Vue.js dynamic image src with webpack require() not working

I'm trying to bind image src dynamically to a URL of the form ../assets/project_screens/image_name.jpg .我正在尝试将图像 src 动态绑定到../assets/project_screens/image_name.jpg形式的 URL。

My directory structure looks like:我的目录结构如下:

- src
 -- assets
   ---- project_screens
 -- profile
   ---- ProjectList.vue 
 -- store
   ---- profile.js

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.我知道我需要使用 webpack 的require("path/to/image")来帮助 webpack 构建这些图像,但是路径没有解析。

// 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>

If I used a URL string instead of dynamically passing the URL string it works.如果我使用 URL 字符串而不是动态传递 URL 字符串,它会起作用。 Looked around stack overflow and none of the solutions helped.环顾堆栈溢出,没有任何解决方案有帮助。 Am I missing something else ?我还缺少其他东西吗?

I finally figured it out!!我终于想通了!! Webpack cannot import the file if its name is completely given as a variable like:如果文件名称完全以变量形式给出,则 Webpack 无法导入文件,例如:

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.这是因为如果路径存储在变量中,它在编译时不知道路径。

But Webpack can detect files to bundle when it is given a string interpolation in require() like:但是 Webpack 可以在 require() 中给定字符串插值时检测要捆绑的文件,例如:

require(`../assets/profile_screens/${filename}`) // Works

This works because Webpack knows the path "../assets/profile_screens" at compile time so it can include all the files inside the folder.这是有效的,因为 Webpack 在编译时知道路径“../assets/profile_screens”,因此它可以包含文件夹中的所有文件。

The syntax below worked for me:下面的语法对我有用:

<img :src="`${project.img_url}`" alt="People" />

It works with full url.它适用于完整的网址。

require() not required. require()不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM