...">

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

According to VueJS docs:

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

I tried several templates:

 <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 invalid for the HTML style attribute.

Any ideas?

+5
source share
4 answers

After trying other templates, this works:

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

Results in:

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

+3
source

Using the computed property works very well and is cleaner:

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

Do it. It also works for templates.

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

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

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

Source: https://habr.com/ru/post/1259940/


All Articles