简体   繁体   中英

In a Vue app, Key Up Event fired on an input element when tabbed into. Why?

Here is the HTML code,

<div id="vue-app">
       <h1>data binding</h1>
       <label>Name:</label>
       <input type="text" v-on:keyup="logName" />
    
       <label>Age:</label>
       <input type="text" v-on:keyup="logAge" />
    
</div>

Here is the script:

new Vue({
    el: '#vue-app',

    methods: {
       logName: function() {
          console.log("You entered your name");
       },

       logAge: function() {
           console.log("You entered your age");
       }
    }
});

Now when I tab into the "Age" input field, it fires the "keyup" event. Why is that so?

tab is a key that fires the v-on:keyup event, use v-on:input event instead of it:

<div id="vue-app">
       <h1>data binding</h1>
       <label>Name:</label>
       <input type="text" v-on:input="logName" />
    
       <label>Age:</label>
       <input type="text" v-on:input="logAge" />
    
</div>

This is expected behaviour, since any key press trigger a keyup event. To prevent tab key from triggering this event you could try:

methods: {
       logName(e) {
          if(e.keyCode === 9) return
          console.log("You entered your name");
       },
       logAge(e) {
           if(e.keyCode === 9) return
           console.log("You entered your age");
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM