虽然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>