2

My question is that I want to load a div image-background dynamically. How can I do this?

<div
      class="sub-service-box"
      v-for="item in serviceCategories[itemIndex].services"
      :key="item._id"
    >
      <div
        class="background-img"
        :style="{ backgroundImage: 'url(' + item.imageUrl + ')' }"
      >
      </div>

    </div>

serviceCategories[itemIndex].services is an array that comes from API

negin motalebi
  • 351
  • 2
  • 15
faezeh
  • 113
  • 2
  • 15
  • Seemly your code hasn't problem. are you sure `item.imageUrl` load any image? – negin motalebi Sep 13 '21 at 05:28
  • Does this answer your question? [CSS set background-image by data-image attr](https://stackoverflow.com/questions/26967890/css-set-background-image-by-data-image-attr) – Phil Sep 13 '21 at 05:32
  • As you cant set style of a pseudo element directly you need to pass it say a CSS variable that has the URL setting. – A Haworth Sep 13 '21 at 05:46
  • 1
    you can solve this problem after reading this [part](https://stackoverflow.com/a/60031052/11530419) – ElsaKarami Sep 13 '21 at 05:56

1 Answers1

-1

Is imageUrl a remote https url, or a path to a static asset in your project?

If it's a remote url your code looks fine.

If it's a static asset in your project, you have to require it like this:

<div
  class="sub-service-box"
  v-for="item in serviceCategories[itemIndex].services"
   :key="item._id"
>
  <div
    class="background-img"
     :style="{ backgroundImage: 'url(' + require(item.imageUrl) + ')' }"
  >
  </div>
</div>
tho-masn
  • 1,126
  • 1
  • 7
  • 13