vue界面实现滑动加减
Vue 实现滑动加减功能
使用 v-model 和 input range
通过 HTML5 的 input[type="range"] 结合 Vue 的 v-model 实现基础滑动加减功能。
<template>
<div>
<input
type="range"
v-model="value"
min="0"
max="100"
@input="updateValue"
>
<span>{{ value }}</span>
</div>
</template>
<script>
export default {
data() {
return {
value: 50
}
},
methods: {
updateValue() {
console.log(this.value);
}
}
}
</script>
添加加减按钮
扩展功能,增加按钮控制数值增减。
<template>
<div class="slider-container">
<button @click="decrement">-</button>
<input
type="range"
v-model="value"
min="0"
max="100"
>
<button @click="increment">+</button>
<span>{{ value }}</span>
</div>
</template>
<script>
export default {
data() {
return {
value: 50
}
},
methods: {
increment() {
if (this.value < 100) this.value++;
},
decrement() {
if (this.value > 0) this.value--;
}
}
}
</script>
<style>
.slider-container {
display: flex;
align-items: center;
gap: 10px;
}
</style>
使用第三方库(如 vue-slider-component)
对于更复杂的滑动控件,可以使用专门的 Vue 滑动组件库。
安装依赖:
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: 50
}
}
}
</script>
自定义样式滑动条
通过 CSS 自定义原生滑动条样式。
<template>
<input
type="range"
class="custom-slider"
v-model="value"
min="0"
max="100"
>
</template>
<style>
.custom-slider {
-webkit-appearance: none;
width: 100%;
height: 8px;
background: #ddd;
outline: none;
}
.custom-slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 20px;
height: 20px;
background: #42b983;
cursor: pointer;
border-radius: 50%;
}
</style>
双向绑定与事件处理
添加实时显示和值变化事件处理。
<template>
<div>
<input
type="range"
v-model="value"
min="0"
max="100"
@change="onChange"
>
<p>当前值: {{ value }}</p>
</div>
</template>
<script>
export default {
data() {
return {
value: 30
}
},
methods: {
onChange() {
alert(`值已修改为: ${this.value}`);
}
}
}
</script>
移动端优化
针对移动设备添加触摸事件支持。
<template>
<div
class="touch-slider"
@touchstart="startDrag"
@touchmove="onDrag"
@touchend="endDrag"
>
<div class="slider-thumb" :style="{ left: thumbPosition + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
value: 0,
isDragging: false,
sliderWidth: 200
}
},
computed: {
thumbPosition() {
return (this.value / 100) * this.sliderWidth;
}
},
methods: {
startDrag(e) {
this.isDragging = true;
this.updateValue(e);
},
onDrag(e) {
if (this.isDragging) this.updateValue(e);
},
endDrag() {
this.isDragging = false;
},
updateValue(e) {
const rect = e.target.getBoundingClientRect();
const x = e.touches[0].clientX - rect.left;
this.value = Math.min(100, Math.max(0, (x / this.sliderWidth) * 100));
}
}
}
</script>
<style>
.touch-slider {
position: relative;
width: 200px;
height: 20px;
background: #eee;
}
.slider-thumb {
position: absolute;
width: 30px;
height: 30px;
background: #42b983;
border-radius: 50%;
top: -5px;
transform: translateX(-50%);
}
</style>





