Vue.js data-bind style backgroundImage not working

后端 未结 9 1313
耶瑟儿~
耶瑟儿~ 2020-12-12 16:18

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(

9条回答
  •  鱼传尺愫
    2020-12-12 16:28

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

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

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

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

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

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

    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:

    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.

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

提交回复
热议问题