Validate an empty input when doing a backspace or 'backspace' with VueJS2

1

In an html I have a v-model='code' with an attribute v-on:change='consultar()' which at the time of typing the code and tabular (for example, (is one of many ways to make the change)), he goes to that method and I list the data in a form, right there!

'The problem'
In the method 'consultar' valid that when the form is empty and when not run the post, the problem is that to validate that the field is empty or not, I should always make a change and the idea is that as long as I do the backspace and know that it's empty I clean the form without having to make the change.

Code
HTML

<input type="text" v-model='code' v-on:change='consultar()' placeholder="ingrese codígo">

VueJS

new Vue({
    el: '#content',
    data: {
        code: '',
        datos: {
            name: '',
            etc..
        } // Aqui van todos los parametros para el formulario
    },
    methods: {
        consultar: function () {
            if (this.code == '') {
                this.datos = {},
            } else {
                // ejecutar el post
            }
        },
    },
})

I appreciate the interest.

    
asked by JDavid 04.12.2018 в 15:50
source

1 answer

1

There is the possibility of placing a 'keyup' or 'keydown' event on your input. Also from there you can specify which key will activate the event.

In your case to receive each time the backspace is pressed:

<input type="text" v-model='code' @keyup.delete='consultar()' placeholder="ingrese codígo">

This will cause that when you press and release the backspace key your "consult" method will be called. If you want it to be specifically for keydown (say, because you want to do a preventDefault to avoid having the action of deleting a character) you can do it too. The reason why this is done with keydown and not keyup is because these default actions of the backspace key are carried out by pressing the key and not by dropping it. Here is an example:

<input type="text" v-model='code' @keydown.delete='consultar()' placeholder="ingrese codígo">
<input type="text" v-model='code' @keydown.delete.prevent='consultar()' placeholder="ingrese codígo"> //Para preventDefault en vuejs. Ten en cuenta que los event modifiers se stackean de dicha manera. También es lo mismo hacer v-on: que usar @

The modifier ".delete" is also activated with the delete key. If you only want to activate with backspace specifically then you must define a Key Code using Vue.config.keyCodes in the following way:

Vue.config.keyCodes = {
  'backspace': 8 //El key 'backspace' definirá el modifier que le agregaremos a nuestro evento keyup/keydown. El número es el ID de dicho botón
}

Having already our key code defined in our APP Vue, we can use it freely.

<input type="text" v-model='code' @keydown.backspace='consultar()' placeholder="ingrese codígo"> //Ahora solo se activará con backspace!

References:

answered by 07.12.2018 в 04:20