【问题标题】:Vue.js focus input inside v-if inside v-forVue.js 焦点输入在 v-if 内 v-for 内
【发布时间】:2021-11-10 08:42:04
【问题描述】:

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

这是我当前的代码:

<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: "",
  };
},

【问题讨论】:

    标签: javascript vue.js input focus


    【解决方案1】:

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

    nextTick 根据 vue 文档的用法:

    将回调推迟到下一个 DOM 更新周期后执行。更改一些数据后立即使用它以等待 DOM 更新。

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

    【讨论】:

    • 感谢您的帮助,这为我解决了问题。实际上是一个非常简单的解决方案,我自己也找不到。
    【解决方案2】:

    请试试这个:

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

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2019-02-27
      • 2020-07-18
      • 2018-08-02
      • 1970-01-01
      • 2018-03-06
      相关资源
      最近更新 更多