Inline style attribute with background-image - How to?


Hello everyone,
first post here so…sorry in advance if the question is a bit silly. :see_no_evil:

I have searched for similar posts, found a few (some of them would not work for me) but I finally ended up doing it in a slightly different way that almost works for me.

Some context: I am building a set of news cards and I need to use images (coming from an API) as background images of a div that is part of this card.

I ended up using a method that does the following:

    methods: {
      getImageUrl: function (newsItem) {        
            return 'background-image: url(' + this.baseurl + newsItem.image_path + 'prev/' + newsItem.image_fileName + ')';

that is used here on the template:

<div class="card-3__image" :style="this.getImageUrl(news.assets_images[0])" />

and finally produces this

<div class="card-3__image" style="background-image: url(&quot;;);">

So this works…but if the image file name contains a parenthesis (such as “image(1).jpg”) it breaks…

Again I am very new to vue (and to any JS framework) so I apologize if this sounds silly but…

  1. Why does it error?
  2. How could it be fixed?
  3. Solving it this way, with a method that returns the inline style attribute and its content, is a good practice?

Thank you in advance for any answer and for reading :slight_smile:


Breaks how, exactly?

Inspect it with devtools, see what styles are applied, check the network tab to see if the image path could be loaded correctly …


Thank you for your reply @LinusBorg!

It does not really “break” but it does not apply the style attribute at all, so I get this:

<div class="card-3__image">

No style attribute is applied to that card (see above) . Network tab indicates the image is not downloaded at all. It looks like the getImageUrl function does not return anything (or fails) and therefore the :style binding for that card div fails.

I will look into debugging that method.
In any case I am very curious to find out if there is any other better way to do this (inline background image style from data) :smiley:

EDIT: I believe I found a fix. Since quotes within background-image url attributes are not mandatory we often don’t add them but in this case they seem to be what fixes it all as having the url of the image wrapped in quotes avoids the parenthesis inside the url string to be interpreted.

So changing this:

methods: {
      getImageUrl: function (newsItem) {        
            return 'background-image: url(' + this.baseurl + newsItem.image_path + 'prev/' + newsItem.image_fileName + ')';

to this:

methods: {
      getImageUrl: function (newsItem) {        
            return 'background-image: url("' + this.baseurl + newsItem.image_path + 'prev/' + newsItem.image_fileName + '")';

seems to fix it :ok_hand:
Hope I am not doing something that is terribly bad practice though :sweat_smile:

Thanks again!


No that looks totally fine.