Files
sunProduct/src/components/LicensePlateInput/index.vue
2026-06-16 15:09:09 +08:00

360 lines
7.4 KiB
Vue

<template>
<div class="license-plate-input">
<div class="plate_line">
<div
v-for="(item, index) in chars"
:key="index"
class="plate-item"
:class="{
active: activeIndex === index,
disabled: disabled,
error: hasError
}"
>
<input
ref="inputRefs"
v-model="chars[index]"
type="text"
maxlength="1"
:disabled="disabled"
@input="onInput(index)"
@keydown="onKeydown($event, index)"
@paste="onPaste"
@focus="activeIndex = index"
@blur="onBlur"
@compositionend="onCompositionEnd(index)"
/>
</div>
</div>
<!-- 错误提示 -->
<transition name="el-fade-in-linear">
<div v-if="hasError && errorMessage" class="plate-error">
{{ errorMessage }}
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { LicensePlateValidator } from '@/utils/Reg';
// 省份简称
const PROVINCES = [
'京',
'津',
'沪',
'渝',
'冀',
'豫',
'云',
'辽',
'黑',
'湘',
'皖',
'鲁',
'新',
'苏',
'浙',
'赣',
'鄂',
'桂',
'甘',
'晋',
'蒙',
'陕',
'吉',
'闽',
'贵',
'粤',
'青',
'藏',
'川',
'宁',
'琼'
];
// 合法基础字符:字母 (排除I,O) 和 数字
const VALID_CHAR_REGEX = /^[A-HJ-NP-Z0-9]$/i;
// 车牌特殊结尾字符
const SPECIAL_CHARS = ['警', '学', '挂', '临', '超', '港', '澳'];
const props = defineProps<{
modelValue: string;
disabled?: boolean;
required?: boolean;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
'change': [value: string];
}>();
const inputRefs = ref<HTMLInputElement[]>([]);
const activeIndex = ref(-1);
const chars = ref<string[]>(Array(8).fill(''));
const hasError = ref(false);
const errorMessage = ref('');
// 外部值同步到内部
watch(
() => props.modelValue,
(val) => {
const cleanVal = (val || '').toUpperCase().trim();
const currentJoined = chars.value.join('').trim();
if (cleanVal !== currentJoined) {
const newChars = Array(8).fill('');
if (cleanVal) {
const arr = cleanVal.split('');
for (let i = 0; i < Math.min(arr.length, 8); i++) {
newChars[i] = arr[i];
}
}
chars.value = newChars;
if (cleanVal) clearError();
}
},
{ immediate: true }
);
// 内部值同步到外部
watch(
chars,
(newChars) => {
const value = newChars.join('').trim();
emit('update:modelValue', value);
emit('change', value);
if (hasError.value) {
clearError();
}
},
{ deep: true }
);
function onInput(index: number) {
let char = chars.value[index];
if (!char) return;
// 统一转大写 (汉字不受影响)
char = char.toUpperCase();
let isValid = false;
// 1. 第一位:必须是省份
if (index === 0) {
if (PROVINCES.includes(char)) {
isValid = true;
}
}
// 2. 特殊字符处理 (警/学/挂/临/超/港/澳)
else if (SPECIAL_CHARS.includes(char)) {
// 特殊字符通常出现在最后一位,或者倒数第二位(如临时车牌的"临"可能在最后,也可能在倒数第二?不,通常是最后)
// 为了用户体验,允许在任何非第一位的位置输入,但最终校验会判断位置是否正确
isValid = true;
}
// 3. 常规字符:字母或数字
else {
if (VALID_CHAR_REGEX.test(char)) {
isValid = true;
}
}
if (!isValid) {
chars.value[index] = '';
return;
} else {
chars.value[index] = char;
// 如果输入的是特殊字符,通常意味着车牌结束,不再自动跳转
// 如果输入的是常规字符,且不是最后一格,则跳转
if (!SPECIAL_CHARS.includes(char) && char && index < 7) {
nextTick(() => {
inputRefs.value[index + 1]?.focus();
});
}
}
}
function onCompositionEnd(index: number) {
onInput(index);
}
function onKeydown(e: KeyboardEvent, index: number) {
if (e.key === 'Backspace') {
if (!chars.value[index] && index > 0) {
e.preventDefault();
nextTick(() => {
inputRefs.value[index - 1]?.focus();
});
}
return;
}
if (e.key === 'ArrowLeft' && index > 0) {
e.preventDefault();
inputRefs.value[index - 1]?.focus();
}
if (e.key === 'ArrowRight' && index < 7) {
e.preventDefault();
inputRefs.value[index + 1]?.focus();
}
}
function onPaste(e: ClipboardEvent) {
e.preventDefault();
const text = e.clipboardData?.getData('text')?.toUpperCase().trim() || '';
if (!text) return;
const filledChars = [...chars.value];
let insertPos = activeIndex.value >= 0 ? activeIndex.value : 0;
for (let i = 0; i < text.length; i++) {
if (insertPos >= 8) break;
const char = text[i];
let canInsert = false;
if (insertPos === 0) {
if (PROVINCES.includes(char)) canInsert = true;
} else if (SPECIAL_CHARS.includes(char)) {
canInsert = true;
} else {
if (VALID_CHAR_REGEX.test(char)) canInsert = true;
}
if (canInsert) {
filledChars[insertPos] = char;
insertPos++;
}
}
chars.value = filledChars;
nextTick(() => {
const focusIdx = Math.min(insertPos, 7);
inputRefs.value[focusIdx]?.focus();
});
}
function onBlur() {
setTimeout(() => {
const hasFocus = inputRefs.value.some((input) => document.activeElement === input);
if (!hasFocus) {
activeIndex.value = -1;
validate();
}
}, 200);
}
function validate(): { valid: boolean; message?: string } {
const value = chars.value.join('').trim();
if (props.required && !value) {
setError('请输入车牌号');
return { valid: false, message: '请输入车牌号' };
}
if (!value) {
clearError();
return { valid: true };
}
if (!LicensePlateValidator.isValidPlate(value)) {
setError('车牌号格式不正确');
return { valid: false, message: '车牌号格式不正确' };
}
clearError();
return { valid: true };
}
function setError(msg: string) {
hasError.value = true;
errorMessage.value = msg;
}
function clearError() {
hasError.value = false;
errorMessage.value = '';
}
defineExpose({
focus: () => nextTick(() => inputRefs.value[0]?.focus()),
clear: () => {
chars.value = Array(8).fill('');
clearError();
emit('update:modelValue', '');
emit('change', '');
},
validate,
clearError
});
</script>
<style scoped>
.license-plate-input {
display: flex;
flex-direction: column;
gap: 4px;
width: fit-content;
}
.plate_line {
display: flex;
align-items: center;
gap: 6px;
}
.plate-item {
width: 32px;
height: 32px;
border: 1px solid #dcdfe6;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
background-color: #fff;
}
.plate-item.active {
border-color: #409eff;
box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
.plate-item.error {
border-color: #f56c6c;
}
.plate-item.disabled {
background-color: #f5f7fa;
cursor: not-allowed;
color: #a8abb2;
}
.plate-item input {
width: 100%;
height: 100%;
border: none;
text-align: center;
font-size: 16px;
font-weight: 500;
background: transparent;
outline: none;
padding: 0;
margin: 0;
color: inherit;
}
.plate-error {
color: #f56c6c;
font-size: 12px;
line-height: 1.5;
margin-top: 2px;
min-height: 18px;
}
</style>