vue实现滑动条
Vue 实现滑动条
在 Vue 中实现滑动条可以通过原生 HTML 的 <input type="range"> 或自定义组件实现。以下是两种常见方法:
使用原生 HTML 滑动条
通过 Vue 双向绑定 (v-model) 控制滑动条的值:

<template>
<div>
<input
type="range"
v-model="sliderValue"
min="0"
max="100"
@input="handleInput"
/>
<p>当前值: {{ sliderValue }}</p>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 50
}
},
methods: {
handleInput(event) {
console.log('滑动值:', event.target.value);
}
}
}
</script>
自定义滑动条组件
通过 CSS 和事件监听实现更灵活的样式:

<template>
<div class="custom-slider">
<div class="slider-track" ref="track" @click="handleTrackClick">
<div
class="slider-thumb"
ref="thumb"
@mousedown="startDrag"
:style="{ left: thumbPosition + '%' }"
></div>
</div>
<span>当前值: {{ currentValue }}</span>
</div>
</template>
<script>
export default {
data() {
return {
currentValue: 50,
thumbPosition: 50,
isDragging: false
}
},
methods: {
startDrag(e) {
this.isDragging = true;
document.addEventListener('mousemove', this.handleDrag);
document.addEventListener('mouseup', this.stopDrag);
},
handleDrag(e) {
if (!this.isDragging) return;
const trackRect = this.$refs.track.getBoundingClientRect();
let position = ((e.clientX - trackRect.left) / trackRect.width) * 100;
position = Math.max(0, Math.min(100, position));
this.thumbPosition = position;
this.currentValue = Math.round(position);
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.handleDrag);
document.removeEventListener('mouseup', this.stopDrag);
},
handleTrackClick(e) {
const trackRect = this.$refs.track.getBoundingClientRect();
const position = ((e.clientX - trackRect.left) / trackRect.width) * 100;
this.thumbPosition = position;
this.currentValue = Math.round(position);
}
}
}
</script>
<style>
.custom-slider {
width: 300px;
margin: 20px;
}
.slider-track {
height: 6px;
background: #ddd;
border-radius: 3px;
position: relative;
cursor: pointer;
}
.slider-thumb {
width: 16px;
height: 16px;
background: #42b983;
border-radius: 50%;
position: absolute;
top: -5px;
transform: translateX(-50%);
cursor: grab;
}
</style>
使用第三方库
如果需要更复杂的功能(如多滑块、垂直滑块),可以引入以下库:
vue-slider-component(推荐)v-range-slidervue-awesome-slider
以 vue-slider-component 为例:
npm install vue-slider-component --save
<template>
<vue-slider v-model="value" :min="0" :max="100" />
</template>
<script>
import VueSlider from 'vue-slider-component';
import 'vue-slider-component/theme/default.css';
export default {
components: { VueSlider },
data() {
return {
value: 30
}
}
}
</script>
注意事项
- 移动端支持需添加触摸事件(
touchstart/touchmove) - 自定义组件时注意性能优化,避免频繁渲染
- 复杂场景建议直接使用成熟库,减少开发成本






