In this tutorial, you’ll learn how to set background image using inline styles in Vue.js.
In Vue.js you can manipulate a DOM element’s inline styles as well as classes using v-bind:style
.
Here’s how you can set a background image using inline styles:
new Vue({
el: "#app",
data: {
image: 'https://picsum.photos/600/200'
}
})
First of all, let’s set an image src, we’ll be using a third-party random image generator Picsum.
<div id="app">
<h2>Inline background image in Vue.js:</h2>
<div v-if="image" style="width:600px; height:200px" :style="{ 'background-image': 'url(' + image + ')' }"></div>
</div>
As you can see, we’ve just set a background image using the :style
(a shorthand for v-bind:style
).
The result:
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-background-image
PS: Make sure you check other Vue.js tutorials, e.g. conditionally add HTML attributes in Vue.js.