skip to Main Content

I want to make my navbar dynamic. I want to change it’s background image.

I try this:

<b-navbar toggleable="lg"v-bind:style="headerStyle">
this.headerStyle = {
                    backgroundImage: 'url("../../assets/img/sky-views/3.png") !important'
                }

When I do that and inspect it I see this:

inspect result

And there is no image, it cant find the image.

But when I add a class to element and give same path to class it show the image.

<b-navbar toggleable="lg" class="header-wrapper">
...
    <style lang="scss">
    .header-wrapper {
            background-image: url("../../assets/img/sky-views/3.png") !important;
        }
    </style>

When I inspect I see:

inspect result 2

What is the point I miss? Why the result path is different? How can I make it properly?

2

Answers


  1. Chosen as BEST ANSWER

    Another way that I found is give dynamic class name.

    <b-navbar toggleable="lg"v-bind:class="headerClass">
    ...
    this.headerClass= 'night'
    ...
    .night {
                background-image: url("../../assets/img/sky-views/nightImage.png") !important;
            }
    </style>
    

  2. When Webpack compiles your Vue application, it knows to convert CSS url() paths to their compiled counterparts. However, this.headerStyle is just an arbitrary object variable in a Vue component script: Webpack doesn’t have the context to transform that URL.

    In an answer to a similar question, the require() function is recommended for asking Webpack to transform the URL. For your script in particular, the new variable would look something like:

    this.headerStyle = {
      backgroundImage: `url("${require('../../assets/img/sky-views/3.png')}") !important`
    }
    

    And you would v-bind:style="headerStyle" the exact same way in the template.

    Note that the output will be dependent on how your build is configured. In my testing, I got a huge base64-encoded string by default in the outputted style attribute (rather than a URL to an asset). However, the end visual result was the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search