Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue controlled inputs

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.

like image 625
maioman Avatar asked Mar 04 '23 08:03

maioman


1 Answers

<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.

like image 80
Ugo Okoro Avatar answered Mar 12 '23 05:03

Ugo Okoro