admin管理员组

文章数量:1279187

I have a form where user can fill an email address and click a plus button against it to create a new one. These input boxes are generated by iterating over an array. When user clicks on the + icon, a new entry is pushed to this array.

Now the new text box is generating fine but I want the cursor to be focused in this one.

I have a form where user can fill an email address and click a plus button against it to create a new one. These input boxes are generated by iterating over an array. When user clicks on the + icon, a new entry is pushed to this array.

Now the new text box is generating fine but I want the cursor to be focused in this one.

Share Improve this question asked Jan 15, 2020 at 10:18 Vijay JoshiVijay Joshi 9597 silver badges17 bronze badges 1
  • 1 can you please share your code? – Abu Sufian Commented Jan 15, 2020 at 10:19
Add a ment  | 

2 Answers 2

Reset to default 8

as @ramakant-mishra told you must use this.$refs, but you need to add ref attribute dynamically on your input element also. let me show you:

new Vue({
  el: '#app',
  data: {
    emails:[]
  },
  methods: {
    add: function (e) {
      let j = this.emails.push("")
      this.$nextTick(() => {
        this.$refs[`email${j - 1}`][0].focus()
      })
    }
  }
})
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(email, i) in emails" :key="i">
    <input v-model="email" :ref="`email${i}`" />
  </div>
  <button @click="add">add</button>
</div>

just don't forget to use $nextTick because the new element is not rendered yet on template

They key is to set ref on all your inputs to the same string like this:

<input type="text" ref="myInputs"/>

Then you will have access to an array called this.$refs.myInputs inside an event handler.

new Vue({
  el: "#app",

  data() {
    return {
      emails: []
    };
  },
  
  methods: {
    addEmail() {
      this.emails.push('whatever');
      this.$nextTick(() => {
          const lastIdx = this.emails.length - 1;
          this.$refs.myInputs[lastIdx].focus();
      });
    }
  }
});
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <input type="button" @click="addEmail()" value="Add Email"/>
  <div v-for="(email, index) in emails" :key="index">
    <input ref="myInputs" type="text" />
  </div>
</div>

Note that below you must put the call to focus() inside a nextTick() in order to give Vue a chance to actually render the email you just added to the list.

本文标签: javascriptVue Set focus to dynamic input boxStack Overflow