Javascript Vue.js 数据绑定样式背景图像不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35242272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:28:04  来源:igfitidea点击:

Vue.js data-bind style backgroundImage not working

javascripthtmlcssvue.js

提问by CosX

I'm trying to bind the src of an image in an element, but it doesn't seem to work. I'm getting an "Invalid expression. Generated function body: { backgroundImage:{ url(image) }".

我正在尝试将图像的 src 绑定到元素中,但它似乎不起作用。我收到“无效的表达式。生成的函数体:{ backgroundImage:{ url(image) }”。

The documentationsays to use either 'Kebab-case' or 'camel-case'.

文件说,为使用“羊肉串情况”或“驼峰”。

<div class="circular" v-bind:style="{ backgroundImage: { url(image) }"></div>

Heres a fiddle: https://jsfiddle.net/0dw9923f/2/

这是一个小提琴:https: //jsfiddle.net/0dw9923f/2/

回答by David K. Hess

The issue is that the value for backgroundImageneeds to be a string like this:

问题是 for 的值backgroundImage需要是这样的字符串:

<div class="circular" v-bind:style="{ backgroundImage: 'url(' + image + ')' }"></div>

Here's a simplified fiddle that's working: https://jsfiddle.net/89af0se9/1/

这是一个有效的简化小提琴:https: //jsfiddle.net/89af0se9/1/

Re: the comment below about kebab-case, this is how you can do that:

回复:下面关于烤肉串的评论,这是你可以做到的:

<div class="circular" v-bind:style="{ 'background-image': 'url(' + image + ')' }"></div>

In other words, the value for v-bind:styleis just a plain Javascript object and follows the same rules.

换句话说, for 的值v-bind:style只是一个普通的 Javascript 对象并遵循相同的规则。

UPDATE: One other note about why you may have trouble getting this to work.

更新:关于为什么您可能无法使其正常工作的另一个说明。

You should make sure your imagevalue is quoted so that the end resulting string is:

您应该确保您的image值被引用,以便最终结果字符串是:

url('some/url/path/to/image.jpeg')

Otherwise, if your image URL has special characters in it (such as whitespace or parentheses) the browser may not apply it properly. In Javascript, the assignment would look like:

否则,如果您的图像 URL 中包含特殊字符(例如空格或括号),浏览器可能无法正确应用它。在 Javascript 中,赋值看起来像:

this.image = "'some/url/path/to/image.jpeg'"

or

或者

this.image = "'" + myUrl + "'"

Technically, this could be done in the template, but the escaping required to keep it valid HTML isn't worth it.

从技术上讲,这可以在模板中完成,但是为了保持有效的 HTML 所需的转义是不值得的。

More info here: Is quoting the value of url() really necessary?

这里有更多信息: 真的有必要引用 url() 的值吗?

回答by mohammad nazari

<div :style="{'background-image': 'url(' + require('./assets/media/img.jpg') + ')'}"></div>

回答by Abdelsalam Shahlol

Binding background image style using a dynamicvalue from v-forloop could be done like this.

可以像这样使用来自v-for循环的动态值绑定背景图像样式。

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

回答by egdavid

Another solution:

另一种解决方案:

<template>
  <div :style="cssProps"></div>
</template>

<script>
  export default {
    data() {
      return {
        cssProps: {
          backgroundImage: `url(${require('@/assets/path/to/your/img.jpg')})`
        }
      }
    }
  }
</script>

What makes this solution more convenient? Firstly, it's cleaner. And then, if you're using Vue CLI (I assume you do), you can load it by webpack.

是什么让这个解决方案更方便?首先,它更干净。然后,如果您使用 Vue CLI(我假设您使用),您可以通过 webpack 加载它。

Note: don't forget that require()is always relative to the current file's path.

注意:不要忘记它require()总是相对于当前文件的路径。

回答by Saud Chougule

<div :style="{ backgroundImage: `url(${post.image})` }">

there are multiple ways but i found template stringeasy and simple

有多种方法,但我发现模板字符串简单易行

回答by coder618

For single repeated component this technic work for me

对于单个重复组件,这项技术对我有用

<div class="img-section" :style=img_section_style >

computed: {
            img_section_style: function(){
                var bgImg= this.post_data.fet_img
                return {
                    "color": "red",
                    "border" : "5px solid ",
                    "background": 'url('+bgImg+')'
                }
            },
}

回答by WDuffy

I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.

我遇到了一个问题,其中文件名中带有空格的背景图像导致样式无法应用。为了纠正这个问题,我必须确保将字符串路径封装在单引号中。

Note the escaped \' in my example below.

请注意下面我的示例中转义的 \' 。

<div :style="{
    height: '100px',
    backgroundColor: '#323232',
    backgroundImage: 'url(\'' + event.image + '\')',
    backgroundPosition: 'center center',
    backgroundSize: 'cover'
    }">
</div>

回答by devzakir

I tried @davidanswer, and it didn't fix my issue. after a lot of hassle, I made a method and return the image with style string.

我尝试了@david 的回答,但并没有解决我的问题。经过很多麻烦,我做了一个方法并返回带有样式字符串的图像。

HTML Code

HTML代码

<div v-for="slide in loadSliderImages" :key="slide.id">
    <div v-else :style="bannerBgImage(slide.banner)"></div>
</div>

Method

方法

bannerBgImage(image){
    return 'background-image: url("' + image + '")';
},