vue实现slider
Vue 实现 Slider 组件
使用原生 HTML 和 Vue 实现基础 Slider
通过 Vue 的 v-model 绑定数据,结合 HTML 的 input 元素实现基础滑块功能。
<template>
<div>
<input
type="range"
v-model="sliderValue"
:min="min"
:max="max"
@input="handleInput"
/>
<span>{{ sliderValue }}</span>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 50,
min: 0,
max: 100
};
},
methods: {
handleInput(event) {
console.log('当前值:', event.target.value);
}
}
};
</script>
自定义样式和功能
通过 CSS 自定义滑块外观,并扩展功能如步进、提示气泡等。
<template>
<div class="custom-slider">
<input
type="range"
v-model="sliderValue"
:min="min"
:max="max"
:step="step"
class="slider"
/>
<div class="tooltip">{{ sliderValue }}</div>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 30,
min: 0,
max: 100,
step: 5
};
}
};
</script>
<style>
.custom-slider {
width: 300px;
margin: 20px;
}
.slider {
width: 100%;
height: 8px;
background: #ddd;
outline: none;
opacity: 0.7;
transition: opacity 0.2s;
}
.slider:hover {
opacity: 1;
}
.tooltip {
text-align: center;
margin-top: 10px;
}
</style>
使用第三方库(如 Vuetify)
对于更复杂的需求,可以使用现成的 UI 库如 Vuetify 提供的滑块组件。
<template>
<v-slider
v-model="sliderValue"
:min="min"
:max="max"
:step="step"
thumb-label
></v-slider>
</template>
<script>
export default {
data() {
return {
sliderValue: 40,
min: 0,
max: 100,
step: 10
};
}
};
</script>
实现范围选择(双滑块)
通过两个滑块绑定实现范围选择功能。
<template>
<div>
<input
type="range"
v-model="minValue"
:min="min"
:max="maxValue"
@input="updateMin"
/>
<input
type="range"
v-model="maxValue"
:min="minValue"
:max="max"
@input="updateMax"
/>
<div>范围: {{ minValue }} - {{ maxValue }}</div>
</div>
</template>
<script>
export default {
data() {
return {
minValue: 20,
maxValue: 80,
min: 0,
max: 100
};
},
methods: {
updateMin() {
if (this.minValue >= this.maxValue) {
this.minValue = this.maxValue - 1;
}
},
updateMax() {
if (this.maxValue <= this.minValue) {
this.maxValue = this.minValue + 1;
}
}
}
};
</script>
响应式设计
结合 Vue 的计算属性或侦听器,实现滑块值的动态响应。
<template>
<div>
<input
type="range"
v-model="sliderValue"
:min="min"
:max="max"
/>
<div :style="{ width: sliderValue + 'px', height: '20px', background: 'blue' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
sliderValue: 50,
min: 0,
max: 100
};
}
};
</script>






