10

According to VueJS docs:

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

I've tried several patterns:

<div v-bind:style="{ background-image: url(item.img), }"></div>

<div v-bind:style="{ 'background-image': url('item.img'), }"></div>

<div v-bind:style='{ backgroundImage: "url(item.img)", }'></div>

But the results are not valid for the HTML style attribute.

Any ideas?

5 Answers 5

12

After trying other patterns, this is the one that works:

<div v-bind:style='{ backgroundImage: "url(" + item.img + ")", }'></div>

Results in:

<div style='{ background-image: url("/img/path/img.jpg"), }'></div>

Sign up to request clarification or add additional context in comments.

Comments

6

based on @T.Abdullaev's answer, this one with extra double quote worked for me.

v-bind:style='{ backgroundImage: `url("${imgUrl}")` }'

Comments

4

Do this. It works also for templates.

<div :style='{ backgroundImage: `url(${item.img})` }'></div>

Comments

3

For me this seemed to work just fine:

 :style="{
      'background-image': 'url(' + require(`../assets/img/${imageName}`) + ')'
  }"

Since all my images were in the assets folder, the images could be accessed using the above pattern.

Comments

2

Using a computed property works very well, and is cleaner:

computed: {
     imageUrl: function() {
         return 'url('+ this.path + ')';
     }
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.