简体   繁体   English

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

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

According to VueJS docs:根据VueJS文档:

<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.但结果对 HTML style属性无效。

Any ideas?有什么想法吗?

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>

Do this.这样做。 It works also for templates.它也适用于模板。

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

基于@T.Abdullaev 的回答,这个带有额外双引号的对我有用。

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

Using a computed property works very well, and is cleaner:使用计算属性效果很好,而且更清晰:

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

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.由于我的所有图像都在资产文件夹中,因此可以使用上述模式访问图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM