Hoe to set a background image in a style attribute with Vue.js?

Sometimes, we want to set a background image in a style attribute with Vue.js.

In this article, we’ll look at how to set a background image in a style attribute with Vue.js.

How to set a background image in a style attribute with Vue.js?

To set a background image in a style attribute with Vue.js, we can set the style prop to an object with the background-image property.

For instance, we write

<template>
  <div>
    <div
      class="card-image"
      :style="{
        'background-image': `url(${require('@/assets/images/cards.jpg')})`,
      }"
    >
      ...
    </div>
  </div>
</template>

to set the style prop to an object with the background-image property set to a string with the path of the background image wrap around url().

@/ is a shorthand for the src folder.

Conclusion

To set a background image in a style attribute with Vue.js, we can set the style prop to an object with the background-image property.