用vue实现滑动输入条
使用 Vue 实现滑动输入条
基础实现(使用原生 input range)
Vue 可以结合 HTML 的原生 input[type="range"] 快速实现滑动输入条功能。以下是一个基础示例:
<template>
<div>
<input
type="range"
v-model="sliderValue"
:min="min"
:max="max"
@input="handleInput"
/>
<p>当前值: {{ sliderValue }}</p>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 50,
min: 0,
max: 100
}
},
methods: {
handleInput() {
console.log('值变化:', this.sliderValue);
}
}
}
</script>
自定义样式滑动条
如果需要自定义样式,可以隐藏原生输入条并用 CSS 重新设计:
<template>
<div class="custom-slider">
<input
type="range"
v-model="sliderValue"
:min="min"
:max="max"
class="slider"
/>
<div class="slider-track">
<div
class="slider-thumb"
:style="{ left: thumbPosition }"
></div>
</div>
<span>{{ sliderValue }}</span>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 30,
min: 0,
max: 100
}
},
computed: {
thumbPosition() {
const range = this.max - this.min;
const percent = (this.sliderValue - this.min) / range * 100;
return `${percent}%`;
}
}
}
</script>
<style>
.custom-slider {
position: relative;
width: 300px;
}
.slider {
position: absolute;
width: 100%;
opacity: 0;
z-index: 2;
height: 40px;
}
.slider-track {
position: relative;
width: 100%;
height: 6px;
background: #ddd;
border-radius: 3px;
}
.slider-thumb {
position: absolute;
width: 20px;
height: 20px;
background: #42b983;
border-radius: 50%;
top: -7px;
transform: translateX(-50%);
}
</style>
使用第三方库(如 vue-slider-component)
对于更复杂的需求,可以使用专门的 Vue 滑动组件库:
-
安装
vue-slider-component:npm install vue-slider-component --save -
基础使用示例:
<template> <vue-slider v-model="value" :min="0" :max="100" :interval="10" tooltip="always" /> </template>
export default { components: { VueSlider }, data() { return { value: 40 } } }
```实现双向滑动条(范围选择)
需要选择范围值时,可以使用数组作为 v-model:
<template>
<vue-slider
v-model="rangeValue"
:min="0"
:max="100"
:tooltip="true"
:range="true"
/>
</template>
<script>
export default {
data() {
return {
rangeValue: [20, 80]
}
}
}
</script>
垂直滑动条实现
通过设置 direction 属性可以创建垂直滑动条:

<template>
<vue-slider
v-model="value"
:min="0"
:max="100"
direction="vertical"
:height="300px"
/>
</template>
注意事项
- 移动端兼容性需要测试 touch 事件
- 自定义样式时注意处理浏览器兼容前缀
- 性能敏感场景避免频繁触发 @input 事件,可使用防抖
- 无障碍访问需要添加适当的 ARIA 属性






