How to pass variable to inline background image in Vue

How to pass variable to inline background image in Vue

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

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

<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

<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

<div class=" bg-no-repeat bg-cover  bg-white hero relative" :style="{ backgroundImage: `url(${backgroundUrl})` }"></div>

import backgroundUrl from '~/assets/img/bg-wp.png'
export default {
  data() {
    return {
      backgroundUrl
    }
  }
}

Import the file and pass it into Vue data binding.

2. Dynamic data

<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>

export default {
  data() {
    return {
      member: {
                name: "Jakz",
                coverImage: "<https://vuejs.org/images/logo.png>"
            }
    }
  }
}

You can directly pass the variable into the inline-style

Leave a Reply

Your email address will not be published. Required fields are marked *

How to pass variable to inline background image in Vue 3
Up Next:

How to store image in Cloudinary Nodejs REST

How to store image in Cloudinary Nodejs REST