实现滑动选择器从离散型的数组中选择

发布于:2025-05-07 ⋅ 阅读:(24) ⋅ 点赞:(0)

1.使用原生的input

详细代码如下:

<template>
  <div class="slider-container">
    <!-- 滑动条 -->
    <input
      type="range"
      v-model.number="sliderIndex"
      :min="0"
      :max="customValues.length - 1"
      step="1"
      class="custom-slider"
    />

    <!-- 均分刻度 -->
    <div class="marks">
      <div 
        v-for="(value, index) in customValues"
        :key="index"
        class="mark"
        :style="{ left: getVisualPosition(index) + '%' }"
      >
        <div class="mark-line"></div>
        <div class="mark-label">{{ value }}</div>
      </div>
    </div>

    <p>当前值: {{ currentValue }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      customValues: [0, 0.1, 0.2, 1, 5, 10, 30, 50, 100],
      sliderIndex: 0
    };
  },
  computed: {
    currentValue() {
      return this.customValues[this.sliderIndex]; 
    }
  },
  methods: {
    getVisualPosition(index) {
      return (index / (this.customValues.length - 1)) * 100; 
    }
  }
};
</script>

<style scoped>
.slider-container {
  position: relative;
  width: 80%;
  margin: 20px auto;
}

.custom-slider{
  margin:0;
}

.custom-slider {
  width: 100%;
}

.marks {
  position: relative;
  height: 20px;
}

.mark {
  position: absolute;
  transform: translateX(-50%);
  text-align: center;
}

.mark-line {
  width: 2px;
  height: 8px;
  background: #666;
  margin: 0 auto;
}

.mark-label {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}
</style>

2.使用elementplus实现

代码如下:

<template>
  <el-slider 
    style='width:60%;margin: 0 auto;' 
    v-model="currentValue" 
    :min="0" 
    :max="marksRange"
    :step="1" 
    :format-tooltip="formatTooltip" 
  />
  <div style="margin-top:30px;text-align:center;">
    当前选中的值:{{ presetValues[currentValue] }}
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'

// 预设的非线性数值
const presetValues: Array<number> = [0, 0.1, 0.2, 1, 5, 10, 30, 50, 100]
// 计算视觉均分跨度
const marksRange = presetValues.length - 1
// 当前选中的下标
const currentValue = ref<number>(0)

// 自定义提示格式化
const formatTooltip = (value: number) => {
  return presetValues[Math.round((value / marksRange) * (presetValues.length - 1))]
}
</script>


网站公告

今日签到

点亮在社区的每一天
去签到