简体   繁体   中英

Focus on next field on pressing enter key in Vuejs

I am trying to add a feature of moving the focus to next field on pressing enter key. This is how I am trying. But this doesn't work for me. I added a debugger in the focusNext method inputs[index + 1].focus(); shows as undefined. Please help me find where I am going wrong. I am using Vue 2.6.12.

<template>
  <div>
    <v-form :model='user'>
      <v-text-field
       label='First Name'
       @keydown.enter="focusNext"
       v-model='user.first_name'>
      </v-text-field>
      <v-text-field
       label='Last Name'
       v-model='user.last_name'>
      </v-text-field>
      <v-select 
       :items="cities"
       attach
       item-text='name'
       item-value='name'
       v-model="user.city"
       label="City">
      </v-select>
      <v-text-field
       label='Phone Number'
       v-model='user.phone_number'>
      </v-text-field>
    </v-form>
  </div>
</template>

<script>
  export default {
   methods: {
    focusNext(e) {
     debugger
     const inputs = Array.from(e.target.form.querySelectorAll('input[type="text"]'));
     const index = inputs.indexOf(e.target);
     if (index < inputs.length) {
      inputs[index + 1].focus();
     }
    }
   }
  }
</script>

Error 1 在此处输入图像描述

Syntax error

EDIT: So, it was pretty hard to hack Vuetify and let it behave like a basic input since it was not sending it's DOM element through @change . So, we achieved it with some hacky watcher and this nextElement.$el.querySelector("[role='button']").click() selector, to emulate a click and open the v-select .

For some reason, it's not working on Codesandbox, so I don't have a link there to share, only my github repo with a working solution.

Here is the chat that we had: https://chat.stackoverflow.com/rooms/228426/focus-on-next-field-on-pressing-enter-key-in-vuejs
Here is how the final result looks like: https://www.loom.com/share/9e504e14ceb44644976c73fb4ced5c1c

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