Search code examples
javascriptvue.jsinputvuejs2focus

Vue.js focus input inside v-if inside v-for


I am making an app where you can add strings to a list and edit them. When I click edit, the <h3> turns into an input field thanks to some v-if/v-show, I would like to add the functionality that when the input appears, the input also immediately gets focused.

Here is my current code:

<div class="card" v-for="(item, index) in list" :key="index">
        <!-- not editing -->
        <div v-if="editing != index + 1">
          <button class="edit-btn" @click="setEditing(item, index)">
            edit
          </button>
          <h3 class="title">{{ index + 1 + ". " + item }}</h3>
          <button class="delete-btn" @click="deleteEntry(index)">
            bin
          </button>
        </div>

        <!-- editing -->
        <div v-show="editing == index + 1">
          <button
            class="edit-btn"
            style="background-color:white;color:grey;border-color:grey;font-weight:bold"
            @click="cancelEdit"
          >
            x
          </button>
          <input
            ref="editInput"
            autocomplete="off"
            @change="console.log(entry)"
            class="edit-input"
            id="edit-input"
            @keyup.enter="saveChanges(index)"
            v-model="entry"
          />
          <button
            class="delete-btn"
            style="background-color:white;border-color:green;color:green"
            @click="saveChanges(index)"
          >
            mark
          </button>
      </div>
    </div>

function

setEditing(entry, index) {
      this.editing = index + 1;
      this.entry = entry;
      var el = this.$refs.editInput[index];
      console.log(el);
      el.focus();
      // document.getElementById("edit-input").focus();
    },

variables

data() {
  return {
    editing: 0,
    newEntry: "",
    list: [],
    error: "",
    entry: "",
  };
},

Solution

  • v-show takes a time to update the DOM so the focus on input is not working correctly. You should put el.focus() inside nextTick.

    nextTick usage according to vue docs:

    Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

    setEditing(entry, index) {
          this.editing = index + 1;
          this.entry = entry;
          var el = this.$refs.editInput[index];
          console.log(el);
          this.$nextTick(() => {
              el.focus();
          })
    },