Range Slider Nuxt JS

Viewed 975

So I have a task, I need to build a calculator based on a range slider in Nuxt that changes the color when the thumb moves and it calculates something at the same time. I've managed to get it to work on a certain level. But when I flip pages, it crashes saying that can't read addEventListener of undefined.

here is the code:

  <div class="range">
<input  v-html="amount" v-model="value" type="range" class="slider" id="amount"  min="0" max="100">
    </div>
     

methods: {
colorSlider(){
const slider = document.querySelector('#amount')
let x = slider.value 
let color = 'linear-gradient(90deg, rgb(249,84,78)' + x+ '%, rgb(224,224,224)' + x +'%)'
slider.style.background=color
}
},
mounted(){
document.querySelector('#amount').addEventListener('mousemove',this.colorSlider)
}

Any ideeas ?

1 Answers

You don’t need an event listener— Vue is reactive, simply tying the slider to a data property via v-model is fine.

Eg:

...
<input type="range" v-model="sliderValue">
...

export default {
  data() {
    return {
      sliderValue: 0
    }
  }
}

Now when you adjust the slider, the value of sliderValue will update. No event listener required.

To use the value of sliderValue for something useful in your template— you should use a computed property, not a method.

export default {
  data() {
    return {
      sliderValue: 0
    }
  },
  computed: {
    sliderBgColor() {
      return `linear-gradient(90deg, rgb(249,84,78) ${this.sliderValue}%, rgb(224,224,224) ${this.sliderValue}%)`
    }
  }
}

Now when you adjust the slider, the data property it’s tied to (sliderValue) via v-model will change. The computed property sliderBgColor notices the change and automatically updated it’s return value. Use the return value of sliderBgColor in your input and you’re done.

<input type="range" v-model="sliderValue" :style="`background: ${sliderBgColor}`"

There’s plenty of information available on computed properties, I’d recommend taking a look at the Vue docs.

Related