Vue.js 使用 v-for 时的资产文件路径

Vue.js assets file path when using v-for

我刚开始使用 Vue.js,加载静态 img(例如我的徽标)时访问资产文件夹非常简单:

<img src="../assets/logo.png">

但是,我正在使用 v-for 使用示例数据创建多个列表项,这是我的模板:

<ul>
    <li v-for="item in items" :key="item.id">
       <img v-bind:src="item.img" v-bind:alt="item.title">
       <h2 class="md-title">{{item.title}}</h2>
    </li>
</ul>

这是在同一个 .vue 文件中声明的示例数据:

export default {
  name: 'front',
  data () {
    return {
      items: [
        {title: 'Google Pixel', img: '../assets/pixel.png', id: 1},
        {title: 'Samsung Galaxy S8', img: '../assets/s8.png', id: 2},
        {title: 'iPhone 7', img: '../assets/iphone.png', id: 3}
      ]
    }
  }
}

我的问题是 imgs 全部 404 这看起来很奇怪,因为相同的路径适用于静态 imgs。如果我使用这样的绝对路径,它就可以工作

https://media.carphonewarehouse.com/is/image/cpw2/pixelBLACK?$xl-standard$

查看文档后我发现了这个 https://vuejs-templates.github.io/webpack/static.html

这或许可以解释,但我已经尝试了建议的每种方法,但都没有成功:

Asset Resolving Rules

  • Relative URLs, e.g. ./assets/logo.png will be interpreted as a module dependency. They will be replaced with an auto-generated URL based on your Webpack output configuration.

  • Non-prefixed URLs, e.g. assets/logo.png will be treated the same as the relative URLs and translated into ./assets/logo.png.

  • URLs prefixed with ~ are treated as a module request, similar to require('some-module/image.png'). You need to use this prefix if you want to leverage Webpack's module resolving configurations. For example if you have a resolve alias for assets, you need to use to ensure that alias is respected.

  • Root-relative URLs, e.g. /assets/logo.png are not processed at all.

这是 webpack 而不是 vue 的问题吗?一个如此易于使用的库会使文件路径之类的东西变得复杂,这似乎很疯狂。

我在 Vue.js' 论坛上发布了这个问题,Linus Borg 回复了我的答案:

Those explanations only refer to asset paths used in HTML or CSS. in these, the respective webpack-loaders can recognize those paths and manage them.

But if you have paths in your Javascript, webpack cannot infer that those strings should be treated as paths (it can't "understand" your program and see that those strings will later be used in HTML), so you have to tell webpack explicitly that those strings are indeed paths to dependencies, by using require().

export default {
  name: 'front',
  data () {
    return {
      items: [
        {title: 'Google Pixel', img: require('../assets/pixel.png'), id: 1},
        {title: 'Samsung Galaxy S8', img: require('../assets/s8.png'), id: 2},
        {title: 'iPhone 7', img: require('../assets/iphone.png'), id: 3}
      ]
    }
  }
}