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:
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:
What is the point I miss? Why the result path is different? How can I make it properly?
2
Answers
Another way that I found is give dynamic class name.
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: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.