在 Vue 中条件渲染后将焦点放在输入字段上

Gur*_*ofu 2 vue.js

目标

单击“编辑”按钮时,将出现输入字段并自动聚焦。

<button v-if="!editingMode" @click="editingMode = !editingMode">edit</button>
<input v-else type="text" value ref="input">
Run Code Online (Sandbox Code Playgroud)
export default {
  name: "App",
  components: {
    HelloWorld
  },
  data: function() {
    return {
      editingMode: false
    };
  },
  methods: {
    onClickButton() {
      this.editingMode = true;
      this.$refs.input.focus();
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

小提琴

问题

因为Vue中的重新渲染是同步的,所以当我们调用 时this.$refs.input.focus(),输入字段可能还没有渲染。我经历过两个案例:

  1. 输入尚未安装。在这种情况下,Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"就会出现。
  2. 没有这个错误,但也没有焦点。看起来输入字段已安装和准备操作之间存在间隔。

小智 5

尝试在this.$nextTick中调用它:

methods: {
  onClickButton() {
    this.editingMode = true;
    this.$nextTick(() => {
      this.$refs.input.focus();
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

https://codesandbox.io/s/sleepy-dew-5mcju