[Vuejs]-Dynamic background image of a div in Vue

1👍

EDIT: Please note that your approach did work. You just didn’t set the width and height on the div so it didn’t appear on the screen.

Working here

Still, I would go with the following approach if you only need to set the backgroundImage with a dynamic url.

[Options API];

<template>
  <div
    :style="{
      backgroundImage: `url(${imageUrl})`,
      width: '100px',
      height: '100px',
    }"
  ></div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      imageUrl:
        "Your image url",
    };
  },
};
</script>

Alternatively using the Composition API [script setup]

<script setup>
import { ref } from "vue";

const imageUrl = ref(
  "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
);
</script>

<template>
  <div
    :style="{
      backgroundImage: `url(${imageUrl})`,
      width: '100px',
      height: '100px',
    }"
  ></div>
</template>

Leave a comment