Search code examples
vue.jsstyles

Vue backgroundImage not showing from local directory


I am trying to assign a background image to my lists items i v-for that will get data from objects like in code below. I have no problem when I am putting https of random img from web but I don't have img showing if I link to my local asset folder. Can you direct me where is the problem please.

My storage file:

    data() {
    return {
      portfolioListData: [
        {
          id: 'id-1',
          date: '2018',
          title: 'Stitching Fairy',
          description: 'Web Design / Development',
          link: 'https://www.stitchingfairy.com/index.html',
          routLink: '/stitchinFiary',
          backgroundImg: {
            backgroundImage: 'url(./assets/StitchingFairyBackground.jpg)'
          } 
        },
        {
          id: 'id-1',
          date: '2018',
          title: 'Stitching Fairy',
          description: 'Web Design / Development',
          link: '~https://www.stitchingfairy.com/index.html',
          routLink: '/stitchinFiary',
          backgroundImg: {
            backgroundImage: 'url(https://media.istockphoto.com/photos/watercolor-textured-background-picture-id887755698?k=6&m=887755698&s=612x612&w=0&h=_yEUF8gLpWjZv5IgwuWkecNVt4X4P7vpuFBKCWIuR44=)'
          }
        }
      ]
    };
  },
  provide() {
    return {
      resources: this.portfolioListData
    };
  }

My element markup: strong text

<template>
  <li>
    <div :style="backgroundImg" class="portfolio-element">
      <base-container>
        <base-half-half>
          <template v-slot:leftSide>
            <div class="left">
              <p>{{ date }} </p>
              <h3>{{ title }}</h3>
              <p>{{ description }}</p>
            </div>
          </template>
          <template v-slot:rightSide>
            <div class="right">
              
            </div>
          </template>
        </base-half-half>
      </base-container>
    </div>
  </li>
</template>

<script>
export default {
  props: ['date', 'title', 'description', 'backgroundImg']
};
</script>

<style lang="scss" scoped>
.portfolio-element {
  background-repeat: no-repeat;
  background-size: cover;
  height: 20rem;
}
</style>

List Element

<template>
    <ul>
        <portfolio-element
        v-for="res in resources"
        :key="res.id"
        :date="res.date"
        :title="res.title"
        :description="res.description"
        :backgroundImg="res.backgroundImg"
        ></portfolio-element>
    </ul>
</template>
<script>

import PortfolioElement from './PortfolioElement.vue';
export default {
    inject: ['resources'],
    components: {
        PortfolioElement
    }
}
</script>

Solution

  • you can use require() for your local assets

    change this line:

    backgroundImage: 'url(./assets/StitchingFairyBackground.jpg)'
    

    to this:

    backgroundImage: `url(${require('./assets/StitchingFairyBackground.jpg')})`