Set the background image using inline styles in Vue.js

in Code Write a comment

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: ''

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>

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. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other Vue.js tutorials, e.g. conditionally add HTML attributes in Vue.js.

I developed a Vue.js starter kit that you can order today

Order Vue.js starter kit

Write a Comment