DEV Community

Jakz ⚡
Jakz ⚡

Posted on

How to pass variable to inline background image in Vue

Cover

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

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
Enter fullscreen mode Exit fullscreen mode

Example from Vue official website

You can use directly from the variable like this

<div class="progress">
   <div class="progress__fill" :style="{width: progress}"></div>
</div>

<script>
export default {
    props : ['percent'],
    data() {
        return {
            progress: this.percent + '%'
        }
    }
}
</script>
Enter fullscreen mode Exit fullscreen mode

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

<div class="box" style="background-image: url('<https://vuejs.org/images/logo.png>')"></div>
Enter fullscreen mode Exit fullscreen mode

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

<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>
Enter fullscreen mode Exit fullscreen mode

Import the file and pass it into Vue data binding.

2. Dynamic data

<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>
Enter fullscreen mode Exit fullscreen mode

You can directly pass the variable into the inline-style

Original submitted from my blog

Top comments (0)