I'd like a text input to accept only a sequence of numbers. Any other char should be ignored silently. Here's a simplified version of my component:
<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>
In React, there's the concept of controlled components, but I can't seem anything similar in Vue.
The workaround I found (which you can see in comments) is to modify the value of the input element manually, but it kind of defeats the purpose of using Vue.
I've also tried using v-model
, but the issue remains.
codesandbox.
<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>
I took a look at your sandbox and made a few modifications, Please check to see if this is what you want, the view is now updated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With