Slider 滑块
滑块组件,用于在一个固定区间内进行数值选择。
组件源码
vue
<script lang="ts" setup>
import { computed } from 'vue';
const $props = withDefaults(
defineProps<{
modelValue?: number;
color?: string;
trackColor?: string;
width?: string;
strokeWidth?: string;
showText?: boolean;
textColor?: string;
min?: number;
max?: number;
step?: number;
disabled?: boolean;
}>(),
{
color: '#525252',
trackColor: '#e5e6eb',
width: '100%',
strokeWidth: '6px',
showText: true,
textColor: '#525252',
min: 0,
max: 100,
step: 1,
disabled: false
}
);
const $emits = defineEmits<{
'update:modelValue': [value: number];
}>();
const level = computed({
get: () => {
return $props.modelValue ?? 0;
},
set: (value: number) => {
$emits('update:modelValue', +value);
}
});
</script>
<template>
<div class="slider">
<input type="range" class="level" v-model="level" :min :max :step :disabled />
<div class="slider-text" v-if="showText">{{ level }}</div>
</div>
</template>
<style lang="scss" scoped>
.slider {
display: flex;
align-items: center;
.level {
overflow: hidden;
appearance: none;
width: v-bind(width);
height: v-bind(strokeWidth);
background-color: v-bind(trackColor);
border-radius: 99px;
cursor: pointer;
&::-webkit-slider-thumb {
appearance: none;
width: 0;
height: 0;
box-shadow: -100vw 0 0 100vw v-bind(color);
}
&:disabled {
cursor: not-allowed;
opacity: 0.3;
}
}
.slider-text {
overflow: hidden;
margin-left: 5px;
width: 42px;
font-size: 14px;
color: v-bind(textColor);
}
}
</style>基础用法
默认样式: 自定义颜色: 自定义步长: 自定义宽度: 禁用状态:
20
30
40
5
64
示例代码
vue
<template>
<div class="container">
默认样式:
<base-slider v-model="value1" />
自定义颜色:
<base-slider v-model="value2" color="#ea3323" track-color="#f3d2d2" text-color="#ea3323" />
自定义步长:
<base-slider v-model="value3" :step="5" />
自定义宽度:
<base-slider v-model="value4" stroke-width="12px" />
禁用状态:
<base-slider v-model="value5" disabled />
</div>
</template>
<script lang="ts" setup>
import BaseSlider from '@/BaseSlider/BaseSlider.vue';
import { ref } from 'vue';
const value1 = ref(20);
const value2 = ref(30);
const value3 = ref(40);
const value4 = ref(5);
const value5 = ref(64);
</script>
<style lang="scss" scoped>
.container {
display: flex;
flex-direction: column;
gap: 5px;
}
</style>API
Props
| 参数名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| modelValue(v-model) | 绑定值 | number | 0 |
| min | 最小值 | number | 0 |
| max | 最大值 | number | 100 |
| step | 步长 | number | 1 |
| disabled | 是否禁用 | boolean | false |
| showText | 是否显示文本 | boolean | true |
| textColor | 文本颜色 | string | #525252 |
| color | 滑块激活态颜色 | string | #525252 |
| trackColor | 滑块轨道颜色 | string | #e5e6eb |
| strokeWidth | 滑块高度 | string | 6px |
| width | 滑块宽度 | string | 100% |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| update:modelValue | 滑块值发生改变时触发 | value: number |