Home > Blockchain >  Vuetify : v-text-field input restore value
Vuetify : v-text-field input restore value

Time:02-20

It's a simple app with v-text-field for input. I want to enable user input for only numbers, if I try to type like 11a and then press tab or click mouse out of input before I lost focus I see 11, but then focus lost I see 11a. I don't understand how last symbol restored and how fix it. What am I doing wrong?

  <div id="app">
    <h1>{{message}}</h1>

    <v-text-field @input.native="setOnlyNumber" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Welcome to Vue!'
    };
  },
  methods: {
    setOnlyNumber(e) {
      e.target.value = e.target.value.replace(/\D /, '');
    }
  }
};
</script>```

It is my example app on codepen
https://codepen.io/aleksandra973/pen/BamYdOO

CodePudding user response:

The easiest way would be to make use of the Number type input of HTML5.

v-text-field can use this type with the following flag:

<v-text-field type='number' />

Alternatively, you could bind to the data and run a validation as follows:

<template>
  <div id="app">
    <h1>{{message}}</h1>

    <v-text-field v-model='number' @change="validate" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Welcome to Vue!',
      number: null,
    };
  },
  methods: {
    validate() {
      this.number = this.number.toString().replace(/\D /, '');
    }
  }
};
</script>

CodePudding user response:

You can use type="number" in <v-text-field> element.

Working Demo :

Vue.use(Vuetify);

var vm = new Vue({
    el: "#app",
  data() {
    return {
      message: 'Welcome to Vue!'
    };
  }
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

<div id="app">
  <h1>{{message}}</h1>
  <v-text-field type="number" label="Number Input Field"/>
</div>

  • Related