【问题标题】:Vue focus on input field when it becomes visible当输入字段变得可见时,Vue会关注输入字段
【发布时间】:2021-11-06 03:00:10
【问题描述】:

我有一个标题 (H1) 和一个编辑按钮。按下按钮时,我想将 h1 切换到输入字段。接下来我想关注输入字段,但该部分不起作用,因为输入字段的引用未定义。我已经尝试使用settimeout 作为解决方法,但这并没有奏效。

任何人都有可行的解决方案?

<template>
    <h1 class="text-gray-900 text-2xl font-medium flex items-center">
        <input v-if="isEditing" ref="name" type="text" v-model="role" @keyup.esc="toggleEdit" />
        <span v-else>{{ role }}</span>
        <button @click="toggleEdit">Edit</button>
    </h1>
</template>

<script>
    export default {
        data() {
            return {
                role: 'Admin',
                isEditing: false,
            };
        },
        methods: {
            toggleEdit() {
                this.isEditing = !this.isEditing;
                this.$refs.name.focus();
            },
        },
    };
</script>

可用代码:Codesandbox

【问题讨论】:

  • 你可以试试这个。$nextTick(()=>{this.$refs.name.focus()})
  • 我知道这不太一样,但一种解决方法是改为使用&lt;h1&gt; 标签contenteditable

标签: vue.js ref


【解决方案1】:

您只需要等待 DOM 更新即可。 这有效:

<template>
  <h1 class="text-gray-900 text-2xl font-medium flex items-center">
    <input
      v-if="isEditing"
      ref="roleName"
      class="text-gray-900 text-2xl font-medium"
      type="text"
      v-model="role"
      @keyup.esc="toggleEditRoleName"
    />
    <span v-else>{{ role }}</span>
    <button
      @click="toggleEditRoleName"
      class="ml-2 h-5 w-5 text-blue-300 cursor-pointer"
      aria-hidden="true"
    >
      Edit
    </button>
  </h1>
</template>

<script>
export default {
  data() {
    return {
      role: "Admin",
      isEditing: false,
    };
  },
  methods: {
    toggleEditRoleName() {
      this.isEditing = !this.isEditing;

      this.$nextTick(() => {
        this.$refs.roleName.focus();
      });
    },
  },
};
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2019-07-16
    • 2020-07-19
    • 2017-08-14
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多