Vue.js 焦点输入在 v-if 内部 v-for 内部

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

我正在制作一个应用程序,您可以在其中向列表添加字符串并进行编辑。当我点击编辑时,由于一些 v-if/v-show,<h3> 变成了一个输入字段,我想添加一个功能,当输入出现时,输入也会立即获得焦点。

这是我当前的代码:

<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>

函数

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();
    },

变量

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

v-show 需要时间来更新 DOM,因此输入的 focus 无法正常工作。你应该把 el.focus() 放在 nextTick.

里面

nextTick 根据 vue 文档的用法:

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();
      })
},

请试试这个:

this.$nextTick(() => this.$refs.editInput[index].focus())