简体   繁体   中英

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

I'm trying to get my images to load via a relative path in Vue.js 2 but something seems off. I'm just getting my feet wet with regard to Vue and would appreciate any pointers. Said images are in the /src/assets/imgs directory.

Below are the relevant code snippets for the component in question.

文件树截图

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

Edit: Added a screenshot of my project's (simple) file tree upon request. Said images are in the 'imgs' folder, of course.

Assuming you're using the webpack template from vue-cli , you can simply use a relative path for static assets .

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

Alternatively, put your images in the static directory and reference them with an absolute path, ie

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

To create a link to list contained in an assets folder via JS in Vue.js you must first import the image:

import img from '@/assets/myImage.png'

Then refer to the imported image file in a variable: image:img,

Then lastly src the img to the img tag: :src="image"

In my case I used ../assets/{name of image} :

src/components/SomeComponent.vue

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

This should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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