How to add a Background Image in Vue.js

How to add a Background Image in Vue.js

In this tutorial, we are going to learn about different ways to add a backgroundImage in the vue app by using inline styles.

Adding background Image

Consider we have a div element and we need to add a background image to it.

Example 1:

<template>
  <div :style="{'background-image':'url(https://vuejs.org/images/logo.png)'}">
  </div>
</template>

In the above example, we used vue object syntax to add the image to a div element.

In object syntax, CSS kebab-case properties are wrapped with single quotes.we also wrapped CSS url() function with quotes otherwise vue treated it as some kind of data property and gives an error.

Example 2 :

If you don’t like using quotes with css kebab-case properties we can also use camelCase properties.

<template>
  <div :style="{backgroundImage:'url(https://vuejs.org/images/logo.png)'}">
  </div>
</template>

Example 3:

Storing the style object inside vue data property.

<template>
  <div :style="image"></div></template>

<script>
export default {
  data() {
    return {
      image: { backgroundImage: "url(https://vuejs.org/images/logo.png)" }    };
  }
};
</script>

Example 4:

If your background image comes from your backend server you can add it like this.

<template>
  <div :style="{backgroundImage:`url(${post.image})`}">
  </div>
</template>