为什么我的图像不加载到Vue.js 2中?

Col*_*ndo 3 javascript vue.js vue-component vuejs2

我正在尝试通过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>
Run Code Online (Sandbox Code Playgroud)

编辑:根据要求添加了我项目的(简单)文件树的屏幕截图。这些图像当然在“ imgs”文件夹中。

小智 9

这应该工作

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

  • 为什么要这样做?请编辑您的问题以包含解释以帮助未来的读者 (5认同)

Phi*_*hil 6

假设您使用的是Webpack模板vue-cli,则只需为静态资产使用相对路径即可。

<img :src="'./assets/imgs/' + source + '.png'"
Run Code Online (Sandbox Code Playgroud)

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

<img :src="'/static/imgs/' + source + '.png'"
Run Code Online (Sandbox Code Playgroud)