Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS v-bind:style for background-image: url()

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?

like image 432
Gus Avatar asked Nov 17 '16 23:11

Gus


5 Answers

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>

like image 96
Gus Avatar answered Oct 16 '22 18:10

Gus


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

v-bind:style='{ backgroundImage: `url("${imgUrl}")` }'
like image 24
蔡佳峰 Avatar answered Oct 16 '22 17:10

蔡佳峰


Do this. It works also for templates.

<div :style='{ backgroundImage: `url(${item.img})` }'></div>
like image 43
T.Abdullaev Avatar answered Oct 16 '22 16:10

T.Abdullaev


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.

like image 3
Shristina Avatar answered Oct 16 '22 17:10

Shristina


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

computed: {
     imageUrl: function() {
         return 'url('+ this.path + ')';
     }
},
like image 2
Fran Iglesias Avatar answered Oct 16 '22 16:10

Fran Iglesias