我想要一个只接受数字序列的文本输入。任何其他字符都应该被忽略。这是我的组件的简化版本:
<template>
<div id="app">
<input :value="tel" @input="setTel" placeholder="only numbers" />
<p>{{ tel }}</p>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
tel: "1234"
}),
methods: {
setTel(v) {
const val = v.target.value.replace(/[^0-9]/g, "");
this.tel = val;
/*this.tel = v.target.value = v.target.value.replace(/[^0-9]/g, "");*/
}
}
};
</script>
在 React 中,有 controlled components 的概念,但我在 Vue 中似乎没有任何相似之处。
我找到的解决方法(您可以在评论中看到)是手动修改输入元素的值,但这有点违背了使用 Vue 的目的。
我也尝试过使用 v-model
,但问题依然存在。
最佳答案
<template>
<div id="app">
<input v-model="tel" v-on:keyup="setTel" placeholder="only numbers" />
<p>{{ tel }}</p>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
tel: "1234"
}),
methods: {
setTel(v) {
const val = v.target.value.replace(/[^0-9]/g, "");
this.tel = val;
/*this.tel = v.target.value = v.target.value.replace(/[^0-9]/g, "");*/
}
}
};
</script>
我查看了您的沙箱并进行了一些修改,请检查这是否是您想要的, View 现已更新。
关于javascript - 只接受数字的 Vue 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195878/