简体   繁体   中英

VueJS, Javascript - Prevent Input slider range less than current value

I currently need to disallow the slider thumb to go less than the current value

For example if the sliderValue is 40, the user cannot slide it to anything less than 40. I am using the v-model for numerous calculations so require it's current value, new value as well as the functionality to not be able to slide anything less than the current value

One way to achieve this, is to use the watch functionality of vue. We save the "current Value" as a data point and v-model a different value. In this case I called it sliderVal .


Dynamic Limit via data

If we watch sliderVal we can evaluate whether its lower or higher than the "current" value and react accordingly.

<template>
  <div class="hello">
    <label for="slider">{{ sliderVal }}</label>
    <input type="range" id="slider" v-model="sliderVal" />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      limitVal: 0,
      sliderVal: 0,
    };
  },
  watch: {
    sliderVal(val) {
      if (Number(val) < Number(this.limitVal)) {
        this.sliderVal = this.limitVal;
      }
      if (Number(val) > Number(this.limitVal)) {
        this.limitVal = val;
      }
    },
  },
};
</script>

A working example can be found here on codeSandbox


One Time Limit via Prop

If you want a version where there's a one-time limit of the current value served via prop, I forked it to act accordingly. Then we have currentVal as a prop which sets the limit for the thumb initially, but won't change when going higher.

<template>
  <div class="hello">
    <label for="slider">{{ sliderVal }}</label>
    <input type="range" id="slider" v-model="sliderVal" />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      sliderVal: 0,
    };
  },
  props: {
    currentVal: {
      type: Number,
      required: true,
      default: 0,
    },
  },
  watch: {
    sliderVal(val) {
      if (Number(val) < Number(this.currentVal)) {
        this.sliderVal = this.currentVal;
      }
    },
  },
  created() {
    this.sliderVal = this.currentVal;
  },
};
</script>

And here is the working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM