vue实现滑动条
Vue 实现滑动条的方法
使用原生HTML5 range input
Vue可以轻松绑定原生HTML5的range类型input元素,实现基础滑动条功能。
<template>
<div>
<input
type="range"
min="0"
max="100"
v-model="sliderValue"
@input="handleInput"
>
<span>{{ sliderValue }}</span>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 50
}
},
methods: {
handleInput(event) {
console.log('当前值:', event.target.value)
}
}
}
</script>
使用第三方组件库
主流UI库如Element UI、Vuetify等都提供现成的滑动条组件,功能更丰富。
Element UI示例:
<template>
<el-slider v-model="value" :show-tooltip="true"></el-slider>
</template>
<script>
export default {
data() {
return {
value: 0
}
}
}
</script>
自定义滑动条组件
需要更个性化的滑动条时,可以自行实现:
<template>
<div class="custom-slider">
<div
class="slider-track"
ref="track"
@click="handleTrackClick"
>
<div
class="slider-thumb"
:style="{ left: thumbPosition + 'px' }"
@mousedown="startDrag"
></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
value: 0,
isDragging: false,
trackWidth: 0
}
},
computed: {
thumbPosition() {
return (this.value / 100) * this.trackWidth
}
},
mounted() {
this.trackWidth = this.$refs.track.offsetWidth
window.addEventListener('mousemove', this.handleDrag)
window.addEventListener('mouseup', this.stopDrag)
},
methods: {
startDrag() {
this.isDragging = true
},
handleDrag(e) {
if (!this.isDragging) return
const rect = this.$refs.track.getBoundingClientRect()
let newValue = ((e.clientX - rect.left) / this.trackWidth) * 100
this.value = Math.max(0, Math.min(100, newValue))
},
stopDrag() {
this.isDragging = false
},
handleTrackClick(e) {
const rect = this.$refs.track.getBoundingClientRect()
this.value = ((e.clientX - rect.left) / this.trackWidth) * 100
}
},
beforeDestroy() {
window.removeEventListener('mousemove', this.handleDrag)
window.removeEventListener('mouseup', this.stopDrag)
}
}
</script>
<style>
.custom-slider {
width: 100%;
padding: 20px 0;
}
.slider-track {
position: relative;
height: 4px;
background: #ddd;
cursor: pointer;
}
.slider-thumb {
position: absolute;
width: 16px;
height: 16px;
background: #409eff;
border-radius: 50%;
top: -6px;
transform: translateX(-50%);
cursor: grab;
}
</style>
实现双向绑定
无论使用哪种方式,都可以通过v-model实现双向数据绑定:
// 父组件
<custom-slider v-model="parentValue"></custom-slider>
// 子组件
export default {
props: ['value'],
methods: {
updateValue(newVal) {
this.$emit('input', newVal)
}
}
}
注意事项
- 移动端支持需要添加touch事件处理
- 性能优化时可考虑使用requestAnimationFrame
- 复杂交互场景建议使用第三方库如vue-draggable等
- 无障碍访问需添加ARIA属性







