Updating background image in css class on imported component in vue

Viewed 691

I want to dynamically change the background-image on a ccs class in an imported component How can I do that?

I have installed 'vue-range-slider' and have imported RangeSlider

The range-slider is set up the following way.

<template>
  <div id="slider_div" >

  <range-slider
      class="slider"
      min="0"
      max="100">
  </range-slider>

 </div>
</template>

<script>
import RangeSlider from 'vue-range-slider'
import 'vue-range-slider/dist/vue-range-slider.css';

export default {
  name: 'susScore',
  data: function() {
    return {
      emoji: "../assets/emoji_small.jpg",
    }
  },
  components: {
    RangeSlider
  }

</script>

<style >
#slider_div{
  margin-top: 95px;
  margin-left: 4%;
}

.slider{
  width:200px;
}

.range-slider-knob {
    background-image: url("../assets/emoji_small.jpg")
}

</style>

In this case I am sending a specific image but I want to send an image dynamically using the data option, emoji, in the component.

Question
How can I dynamically update the background-image in the imported .range-slider-knob class?

I tried using CSS variables in a previous question here on SO (Dynamically add image with css variable in vue) but got the reply that that wasn't possible

2 Answers

You can't use vm properties in <style> tag, but you can update emoji in data to:

emoji: require("../assets/emoji_small.jpg")

... and then pass it to any template element using:

<whatever :style={backgroundImage: `url(${emoji})`} />

A fully working example: codesanbox.

I combined require() with a computed changing loaded image based on slider value.

In the RangeSlider.vue file, line 13 shows that the component includes a named slot 'knob'. Vue Slots let you pass html/vue content into the component.

You could pass in a simple div on which you can dynamically change it's background using a method like @tao suggested. Note that a name attribute is given to match the name of the slot you are trying to replace; however, the name shouldn't be required because it is the only slot within component you are using.

<range-slider
   class="slider"
   min="0"
   max="100">
   <div
      name="knob"
      :style={backgroundImage: url(emoji)}
   />
</range-slider>

This method also gives you more freedom in how the knob is presented and/or manipulated with JS.

Related