当前位置: 首页 > news >正文

vue3:触发自动el-input输入框焦点

问:

怎么自动触发el-input输入框焦点

回答:

方法一:使用 nextTick + 组件暴露的 focus 方法(推荐)

import { nextTick } from 'vue';onMounted(async () => {await nextTick(); // 等待DOM更新完成if (searchInputRef.value) {searchInputRef.value.focus();}
});

方法二:使用 watch + nextTick(更保险)

import { watch, nextTick } from 'vue';// 监听组件是否已经挂载并准备好
watch(() => searchInputRef.value,(newVal) => {if (newVal) {nextTick(() => {newVal.focus();});}},{ immediate: true } // 立即执行一次
);

方法三:使用自定义指令(最优雅)

// 全局或局部注册指令
const vFocus = {mounted(el, binding) {const input = el.querySelector('input') || el.querySelector('.el-input__inner');if (input) {// 使用 requestAnimationFrame 确保在浏览器渲染周期内执行requestAnimationFrame(() => {input.focus();});}}
};// 在模板中使用
<el-inputv-focusref="searchInputRef"// ...其他属性
>
</el-input>

方法四:使用 Intersection Observer(适用于需要滚动的场景)

onMounted(() => {if (!searchInputRef.value) return;const observer = new IntersectionObserver((entries) => {entries.forEach(entry => {if (entry.isIntersecting) {nextTick(() => {searchInputRef.value.focus();});observer.disconnect(); // 执行一次后断开观察}});});observer.observe(searchInputRef.value.$el);
});

方法五:组合式函数(最可复用)

// 创建 useAutoFocus.js
import { ref, onMounted, nextTick } from 'vue';export function useAutoFocus() {const targetRef = ref(null);const focus = async () => {await nextTick();if (targetRef.value) {targetRef.value.focus();}};onMounted(focus);return {targetRef,focus};
}// 在组件中使用
import { useAutoFocus } from './useAutoFocus';const { targetRef: searchInputRef } = useAutoFocus();

方法六:使用 Promise 和 requestAnimationFrame(最保险)

onMounted(() => {const focusInput = () => {return new Promise((resolve) => {requestAnimationFrame(() => {if (searchInputRef.value) {searchInputRef.value.focus();resolve(true);} else {resolve(false);}});});};// 尝试多次,直到成功const tryFocus = async (maxAttempts = 5) => {for (let i = 0; i < maxAttempts; i++) {const success = await focusInput();if (success) break;await new Promise(resolve => setTimeout(resolve, 50)); // 短暂延迟}};tryFocus();
});

推荐方案

最推荐使用第一种方法(nextTick),因为:

  1. 官方推荐:Vue 内置的 nextTick 是处理DOM更新后操作的标准方式

  2. 性能更好:比 setTimeout 更高效

  3. 更可靠:确保在组件完全渲染后才执行焦点设置

  4. 代码简洁:不需要猜测延迟时间

// 最佳实践
onMounted(async () => {await nextTick();searchInputRef.value?.focus();
});

这样既避免了 setTimeout 的不确定性,又保证了代码的可靠性和可维护性


文章转载自:

http://gHuB0XY5.gjqwt.cn
http://4PMpqu6A.gjqwt.cn
http://QtelGWY5.gjqwt.cn
http://DeYaPEUw.gjqwt.cn
http://LYIAP1fh.gjqwt.cn
http://goyndFvM.gjqwt.cn
http://XokroByL.gjqwt.cn
http://0wwAsJ5F.gjqwt.cn
http://AlIBkNjf.gjqwt.cn
http://mafjSPiO.gjqwt.cn
http://ox6lqEZn.gjqwt.cn
http://694Anmcu.gjqwt.cn
http://2z8s0Y4i.gjqwt.cn
http://4NwaXtLC.gjqwt.cn
http://MnLoT29h.gjqwt.cn
http://K1L6EoKJ.gjqwt.cn
http://Z9ybREHC.gjqwt.cn
http://f8m4IhSi.gjqwt.cn
http://kTWQmORF.gjqwt.cn
http://JdJ2g1i2.gjqwt.cn
http://hYaaEgQR.gjqwt.cn
http://nxNBLyat.gjqwt.cn
http://mzR4s8Jm.gjqwt.cn
http://AnlQhgrt.gjqwt.cn
http://fMW9LUlp.gjqwt.cn
http://aVVncubG.gjqwt.cn
http://1iedNECq.gjqwt.cn
http://nfKliWLu.gjqwt.cn
http://4fbE6j6V.gjqwt.cn
http://ccXwYEte.gjqwt.cn
http://www.dtcms.com/a/377531.html

相关文章:

  • python range函数练习题
  • Q2(门座式)起重机司机的理论知识考试考哪些内容?
  • 企业微信消息推送
  • 顺序表:数据结构中的基础线性存储结构
  • 什么是X11转发?
  • OpenCV计算机视觉实战(24)——目标追踪算法
  • 4.2 I2C通信协议
  • Spring Boot 读取 YAML 配置文件
  • 【系统分析师】第20章-关键技术:微服务系统分析与设计(核心总结)
  • SAP-MM:SAP MM模块精髓:仓储地点(Storage Location)完全指南图文详解
  • Shell脚本周考习题及答案
  • 广东省省考备考(第九十六天9.10)——言语(刷题巩固第二节课)
  • Pthread定时锁与读写锁详解
  • Go模块自动导入教学文档
  • 技术文章大纲:开学季干货——知识梳理与经验分享
  • TensorFlow平台介绍
  • Vue3 中实现按钮级权限控制的最佳实践:从指令到组件的完整方案
  • 生成模型与概率分布基础
  • Cookie之domain
  • JavaSSM框架-MyBatis 框架(五)
  • 中州养老:设备管理介绍
  • 【Day 51|52 】Linux-tomcat
  • MySQL - 如果没有事务还要锁吗?
  • “高德点评”上线,阿里再战本地生活
  • JUC的常见类、多线程环境使用集合类
  • 《C++ 108好库》之1 chrono时间库和ctime库
  • C++篇(7)string类的模拟实现
  • 弱加密危害与修复方案详解
  • 【Linux】Linux常用指令合集
  • Android- Surface, SurfaceView, TextureView, SurfaceTexture 原理图解