我想要创建输入,如果模式不匹配,我可以用空字符替换输入的字符。
模板:
<input
type="text"
:value="val"
@input="input"
/>剧本:
import { ref } from "vue";
export default {
setup() {
let val = ref("");
const input = ({ target }) => {
val.value = target.value.replace(/[^\d]/g, "");
};
return { val, input };
},
};发布于 2022-09-18 08:58:56
您可以使用观察者删除输入的数字:
const { ref, watch } = Vue
const app = Vue.createApp({
setup() {
let val = ref("");
watch(val,
(newValue, oldValue) => {
val.value = newValue.replace(/\d+/g, "")
},
);
return { val };
},
})
app.mount('#demo')<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div>
<input
type="text"
placeholder="Full Name"
autocomplete="off"
v-model="val"
/>
</div>
{{ val }}
</div>
发布于 2022-09-18 08:05:18
如果您想让用户只输入数字,您也可以使用<input type="number">在HTML中进行本机输入。
发布于 2022-09-18 10:06:34
在代码中,当模式匹配时,您将替换内容。根据您的问题,当模式不匹配时,您希望使其为空。
setup() {
let val = ref("");
const input = ({ target }) => {
if (target && !target.value) val.value = "";
if (!/[^\d]/g.test(target.value)) {
val.value = "";
}
val.value = target.value;
// val.value = target.value.replace(/[^\d]/g, "");
};
return { val, input };
},如果您也希望在更多的输入字段中实现,那么更好的方法是发出指令。
const app = createApp({})
app.directive('text-format', {
mounted(el, binding) {
el._listner = el.addEventListener("input", (e) => {
if (!binding.value.test(el.value)) {
el.value = "";
}
});
},
unmounted(el) {
el.removeEventListener("input", el._listner);
},
})现在您的输入字段
<input
v-text-format="/[^\d]/g"
type="text"
placeholder="Full Name"
autocomplete="off"
v-model="val"
/>https://stackoverflow.com/questions/73760974
复制相似问题