vue3+element-plus el-input 自动获取焦点

虽然element有提供input的autofocus属性,但是当我们第二次进入页面就会发现autofocus已经不再生效,需要通过onMounted去触发input的focus解决这个问题。

1.先给el-input绑定一个ref:
<el-input ref="inputRef" v-model="inpValue" clearable />

2.定义一个函数去触发这个input的focus:
const focusInput = () => {
nextTick(() => {
inputRef.value.focus()
})
}

3.最后通过onMounted去触发这个函数:
onMounted(() => {
focusInput()
})

整体代码就是:

html 复制代码
<template>
  <div class="use_wrap">
    <div class="content">
      <el-input ref="inputRef" v-model="inputValue" placeholder="请输入" clearable />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
const inputRef = ref()
const inputValue = ref('')
onMounted(() => { focusInput() })
const focusInput = () => {
  nextTick(() => {
    inputRef.value.focus()
  })
}
</script>
相关推荐
FIN66681 天前
射频技术领域的领航者,昂瑞微IPO即将上会审议
前端·人工智能·前端框架·信息与通信
U.2 SSD1 天前
ECharts漏斗图示例
前端·javascript·echarts
江城开朗的豌豆1 天前
我的小程序登录优化记:从短信验证到“一键获取”手机号
前端·javascript·微信小程序
excel1 天前
Vue Mixin 全解析:概念、使用与源码
前端·javascript·vue.js
IT_陈寒1 天前
Java性能优化:这5个Spring Boot隐藏技巧让你的应用提速40%
前端·人工智能·后端
勇往直前plus1 天前
CentOS 7 环境下 RabbitMQ 的部署与 Web 管理界面基本使用指南
前端·docker·centos·rabbitmq
北海-cherish1 天前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
2501_915909061 天前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
white-persist1 天前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
新中地GIS开发老师1 天前
Cesium 军事标绘入门:用 Cesium-Plot-JS 快速实现标绘功能
前端·javascript·arcgis·cesium·gis开发·地理信息科学