49 lines
1.8 KiB
Vue
49 lines
1.8 KiB
Vue
<template>
|
|
<div class="aa-numrange" :class="{ 'is-error': !!errorMsg }">
|
|
<input type="number" :value="modelValue[0]" :step="step" :min="min" :max="max"
|
|
:placeholder="placeholder[0]" @input="onMin" />
|
|
<span class="aa-numrange-sep">{{ separator }}</span>
|
|
<input type="number" :value="modelValue[1]" :step="step" :min="min" :max="max"
|
|
:placeholder="placeholder[1]" @input="onMax" />
|
|
<span class="aa-numrange-unit" v-if="unit">{{ unit }}</span>
|
|
<span class="aa-numrange-msg" v-if="errorMsg">{{ errorMsg }}</span>
|
|
</div>
|
|
</template>
|
|
|
|
<script setup>
|
|
import { ref } from 'vue';
|
|
const props = defineProps({
|
|
modelValue: { type: Array, default: () => ['', ''] },
|
|
step: { type: Number, default: 1 },
|
|
min: { type: Number, default: -Infinity },
|
|
max: { type: Number, default: Infinity },
|
|
separator: { type: String, default: '—' },
|
|
unit: { type: String, default: '' },
|
|
placeholder: { type: Array, default: () => ['最小', '最大'] }
|
|
});
|
|
const emit = defineEmits(['update:modelValue', 'error']);
|
|
const errorMsg = ref('');
|
|
|
|
function validate(arr) {
|
|
const a = parseFloat(arr[0]), b = parseFloat(arr[1]);
|
|
let err = '';
|
|
if (arr[0] !== '' && (a < props.min || a > props.max)) err = `最小值需在 ${props.min}~${props.max}`;
|
|
else if (arr[1] !== '' && (b < props.min || b > props.max)) err = `最大值需在 ${props.min}~${props.max}`;
|
|
else if (arr[0] !== '' && arr[1] !== '' && a > b) err = '最小值不能大于最大值';
|
|
errorMsg.value = err;
|
|
emit('error', err);
|
|
}
|
|
function onMin(e) {
|
|
const arr = [e.target.value, props.modelValue[1]];
|
|
validate(arr);
|
|
emit('update:modelValue', arr);
|
|
}
|
|
function onMax(e) {
|
|
const arr = [props.modelValue[0], e.target.value];
|
|
validate(arr);
|
|
emit('update:modelValue', arr);
|
|
}
|
|
</script>
|
|
|
|
<style src="./NumberRangeInput.css"></style>
|