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

2019-06-23 10:54发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2019-06-23 11:18

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

v-bind:style='{ backgroundImage: `url("${imgUrl}")` }'
查看更多
贪生不怕死
3楼-- · 2019-06-23 11:27

Do this. It works also for templates.

<div :style='{ backgroundImage: `url(${item.img})` }'></div>
查看更多
等我变得足够好
4楼-- · 2019-06-23 11:38

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>

查看更多
萌系小妹纸
5楼-- · 2019-06-23 11:39

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

computed: {
     imageUrl: function() {
         return 'url('+ this.path + ')';
     }
},
查看更多
登录 后发表回答