vue3中 input 自动获取焦点

发布于 2023年7月27日热度 342

在Vue 3中,你可以使用ref和v-bind指令来获取焦点。

<template>
  <div>
    <input type="text" :focus="isFocused" ref="myInput"/>
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const isFocused = ref(false);
const myInput = ref(null);

const focusInput = () => {
  isFocused.value = true;
  myInput.value.focus();
  isFocused.value = false; // 重置 isFocused 值
  $nextTick(() => {
    isFocused.value = true;
    myInput.value.focus();
  });
};
</script>

如果input是隐藏的,需要点击后才显示,可以使用setTimeout来延迟获取焦点

const focusInput = () => { 
   setTimeout(() => {
      isFocused.value = true;
      myInput.value.focus();
      isFocused.value = false; // 重置 isFocused 值
      $nextTick(() => {
        isFocused.value = true;
        myInput.value.focus();
      });
    }, 100); 
};