1

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 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.