为什么我的图片无法加载到 Vue.js 2?

Why don't my images load in Vue.js 2?

我试图通过 Vue.js 2 中的相对路径加载我的图像,但似乎有些问题。关于 Vue,我刚刚开始涉足,非常感谢任何指点。所述图像在 /src/assets/imgs 目录中。

下面是相关组件的相关代码片段。

<template>
  <section class="container sources">
        <h2>{{ heading }}</h2> 
        <div class="columns">
            <div class="column" v-for="source in sources">
                <figure :title="source">
                    <img :src="imgPath + source + '.png'" :alt="source + ' logo'">
                    <figcaption>{{ source }}</figcaption>        
                </figure>        
            </div>
        </div>
    </section>
</template>

<script>
export default {
   name: 'sources',
   data () {
      return {
          heading: 'News Sources',
          imgPath: 'src/assets/imgs/',
          sources: [
            'al-jazeera-english', 'associated-press', 'bbc-news', 'bbc-sport', 'business-insider', 'cnn', 
            'daily-mail', 'entertainment-weekly', 'espn', 'financial-times', 'fox-sports', 'hackernews', 
            'ign','independent', 'mtv-news', 'national-geographic', 'new-scientist', 'reuters', 'techcrunch', 'the-economist', 'the-guardian-uk', 'the-huffington-post', 'the-new-york-times', 
                'the-washington-post'
           ]
      }
   }
}
</script>

编辑: 根据要求添加了我的项目(简单)文件树的屏幕截图。当然,上述图像位于 'imgs' 文件夹中。

假设您正在使用来自 vue-cli 的 webpack 模板,您可以简单地使用 static assets.

的相对路径
<img :src="'./assets/imgs/' + source + '.png'"

或者,将您的图像放在 static 目录中并使用绝对路径引用它们,即

<img :src="'/static/imgs/' + source + '.png'"

要在 Vue.js 中通过 JS 创建包含在资产文件夹中的 link 列表,您必须首先导入图像:

从“@/assets/myImage.png”导入 img

然后在一个变量中引用导入的图片文件: image:img,

然后最后将img src到img标签: :src="image"

在我的例子中,我使用了 ../assets/{图像名称} :

src/components/SomeComponent.vue

<style>
    .black.square{
        background: url(../assets/logo.png);
    }
</style>

这应该有效

<img :src="image" >
data () {
  return {
    image: require('@/assets/images/pin.svg')
  }
},