今天在刷思否的时候遇到这样的一个问题:
<template>
<input type="text" :value="inputValue" @input="handleInput" />
</template>
<script setup>
import { ref } from 'vue'
const inputValue = ref('')
const handleInput = (e) => {
const val = e.target.value
const reg = /^\d*$/
if (reg.test(val)) {
inputValue.value = val
} else {
inputValue.value = ''
}
}
</script>
题主希望通过正则校验去限制输入框只能输入数字类型的值,但是只有在先输入数字再输入非数字的情况下才会被正确置空。如果一开始就是输入非数字的内容,后续即使继续输入非数字内容,输入框中的内容并不会清空。
我们可以在 Vue SFC Playground 中体验这个现象。