Sometimes, we want to set the background image of an element with Vue.js.
In this article, we’ll look at how to set the background image of an element with Vue.js.
Set the Background Image of an Element with Vue.js
We can set the background image of an element with Vue.js by setting the ‘background-image'
property to the path of the background image.
For instance, we can write:
<template>
<div id="app">
<div
:style="{
'background-image': `url(${require(image)})`,
width: '100px',
height: '100px',
}"
></div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
image: "@/assets/logo.png",
};
},
};
</script>
to do this.
We add the style
prop with the 'background-image'
property to set the background-image
CSS property.
Then we pass in the image path with require
with the image path in the Vue project folder to compute the correct path.
Now when we should see the background image displayed.
Conclusion
We can set the background image of an element with Vue.js by setting the ‘background-image'
property to the path of the background image.