vue3 input 获取焦点
时间: 2025-03-24 15:24:30 浏览: 36
### Vue3 中实现 Input 自动聚焦的方法
在 Vue3 中,可以通过多种方式实现 `input` 元素的自动聚焦。以下是几种常见的实现方法:
#### 方法一:使用 `$refs` 和 `this.$nextTick`
通过定义组件中的 `ref` 属性来绑定 DOM 节点,在生命周期钩子函数中调用 `this.$nextTick()` 来确保 DOM 已经渲染完成后再执行 `.focus()` 操作。
```javascript
// 使用 $refs 的方式
export default {
mounted() {
this.$nextTick(() => {
this.$refs.myInput.focus(); // 让 input 获取焦点
});
}
};
```
这种方法适用于简单的场景,并且依赖于 Vue2 风格的选项 API[^1]。
---
#### 方法二:使用 Composition API (`setup`) 和 `shallowRef`
在 Vue3 的组合式 API 中,推荐使用 `shallowRef` 或者 `ref` 来管理 DOM 引用。结合 `onMounted` 生命周期钩子以及 `nextTick` 可以轻松实现输入框的自动聚焦。
```html
<template>
<el-input ref="isFocus"></el-input>
</template>
<script setup>
import { shallowRef, onMounted, nextTick } from 'vue';
const isFocus = shallowRef(null);
onMounted(() => {
nextTick(() => {
isFocus.value?.focus(); // 确保 DOM 渲染完成后触发 focus()
});
});
</script>
```
此方法利用了 Vue3 提供的新特性——Composition API,更加灵活和现代化[^2]。
---
#### 方法三:动态索引下的多输入框聚焦
如果页面中有多个动态生成的输入框,则需要借助数组索引来区分不同的输入框实例。可以在点击事件或其他操作时设置标志位并延迟加载对应的输入框焦点。
```javascript
methods: {
toEdit(row, index) {
row.flag = true;
this.$nextTick(() => {
this.$refs[index]?.focus(); // 动态指定某个特定输入框获得焦点
});
},
},
```
上述代码片段展示了当用户进入编辑状态时如何让当前行关联的输入框获取到键盘光标位置[^3]。
---
#### 方法四:直接绑定 Ref 并调用 Focus 函数
对于单个静态输入框来说,也可以采用更简洁的方式来进行初始化处理:
```html
<!-- HTML -->
<input type="text" ref="inputSelectBound">
<script setup>
import { ref, onMounted, nextTick } from 'vue'
const inputSelectBound = ref(null)
onMounted(() => {
nextTick(() => {
inputSelectBound.value?.focus();
})
})
</script>
```
这种方式简单明了,适合只需要一次性的基本需求场合[^4]。
---
### 总结
以上四种方案分别针对不同复杂度的应用场景提供了相应的解决方案。开发者可以根据实际项目的需求选择最合适的策略去达成目标即令 `<input>` 控件成功取得用户的交互注意力。
阅读全文
相关推荐


















