EricTalv
EricTalv

Reputation: 1049

Change element background-image inside a v-for

I have a v-for thats reading different .md files which have a image property in their front matter.

I am trying to change my div's background-image But it has to read that url taken from the files frontmatter.

this is the code:

<div v-for="item in projectsList" class="li" >
                    <div style="background-image: url(https://i.pinimg.com/originals/4f/c4/92/4fc49228a940e41435b3796c18fc2346.jpg)">
                        <a :href="item.path" class="li">
                            <span>{{ item.title }}</span>                       
                        </a>
                    </div>
                </div>

Now the issue lies in changing the style:"background-image: url(<URL>) property.

I can access the image through item.frontmatter.image,

I read about this so i tried to do an example and just for testing purposes tried to feed an image through the Data function, but to vue the Url is undefined so i need a different way of feeding a URL based image to the background.

:style:"{'background-image': url( imageURL )}"

data: function () {
            return {
                imageURL: 'https://i.pinimg.com/originals/4f/c4/92/4fc49228a940e41435b3796c18fc2346.jpg' 

            }
        },

Upvotes: 0

Views: 33

Answers (1)

ajobi
ajobi

Reputation: 3116

You should be able to do it like this:

<div v-for="item in projectsList" class="li" >
  <div :style="{ 'background-image': `url(${item.frontmatter.image})` }">
    <a :href="item.path" class="li">
      <span>{{ item.title }}</span>
    </a>
  </div>
</div>

No data function needed here I think.

Upvotes: 1

Related Questions