How To Pass Variable To Inline Background Image In Vue

May 28, 2019 (5y ago)

If you prefer to watch a video, you can watch it over here  - https://youtu.be/7GCFDL3c8Vo

Passing a style binding into Vue is easy. You can pass like this

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
``` Example from Vue official website You can use directly from the variable
like this ```vue
<template>
  <div class="progress">
    <div class="progress__fill" :style="{ width: progress }"></div>
  </div>
</template>
 
<script>
  export default {
    props: ["percent"],
    data() {
      return {
        progress: this.percent + "%",
      };
    },
  };
</script>
``` If you’re same like me, which is I liked to use image as a background image
into the div. I think this kind of method will make the div has a consistent
size when the browser is changing and can handle different type of image size.
Normal HTML would look like this ```vue
<div
  class="box"
  style="background-image: url('https://vuejs.org/images/logo.png')"
></div>
``` But how would you pass the data if the background image is dependent on the
data binding; It’s a little bit messy because we need to deal with special
characters in one string. There are 2 ways to handle it. ## 1. If you have a
static data ```vue
<template>
  <div
    class=" bg-no-repeat bg-cover  bg-white hero relative"
    :style="{ backgroundImage: `url(${backgroundUrl})` }"
  ></div>
</template>
 
<script>
  import backgroundUrl from "~/assets/img/bg-wp.png";
  export default {
    data() {
      return {
        backgroundUrl,
      };
    },
  };
</script>
``` Import the file and pass it into Vue data binding. ## 2. Dynamic data ```vue
<template>
  <div
    class="min-h-screen bg-grey bg-cover flex items-end block md:fixed w-full md:w-1/2 shadow-md"
    :style="{ backgroundImage: `url(${member.coverImage})` }"
  >
    <p>{{ member.name }}</p>
  </div>
</template>
 
<script>
  export default {
    data() {
      return {
        member: {
          name: "Jakz",
          coverImage: "<https://vuejs.org/images/logo.png>",
        },
      };
    },
  };
</script>
``` You can directly pass the variable into the inline-style I’ve recorded a
video to show how this works.