vue 实现获取焦点
Vue 实现获取焦点的方法
在 Vue 中实现获取焦点可以通过多种方式,以下是几种常见的实现方法:
使用 ref 和 $refs
通过 ref 属性标记元素,然后在方法中调用 focus() 方法:
<template>
<input ref="inputRef" />
<button @click="focusInput">获取焦点</button>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.inputRef.focus()
}
}
}
</script>
使用 v-focus 自定义指令
创建一个自定义指令来自动聚焦元素:
<template>
<input v-focus />
</template>
<script>
export default {
directives: {
focus: {
inserted(el) {
el.focus()
}
}
}
}
</script>
使用 autofocus 属性
对于简单的场景,可以直接使用 HTML5 的 autofocus 属性:
<template>
<input autofocus />
</template>
在 mounted 钩子中获取焦点
当组件挂载完成后自动获取焦点:
<template>
<input ref="inputRef" />
</template>
<script>
export default {
mounted() {
this.$refs.inputRef.focus()
}
}
</script>
使用 nextTick 确保 DOM 更新
在某些需要等待 DOM 更新的情况下使用:

<template>
<input ref="inputRef" v-if="showInput" />
<button @click="showInput = true">显示并聚焦输入框</button>
</template>
<script>
export default {
data() {
return {
showInput: false
}
},
watch: {
showInput(newVal) {
if (newVal) {
this.$nextTick(() => {
this.$refs.inputRef.focus()
})
}
}
}
}
</script>
以上方法可以根据具体需求选择使用,ref 方式最为灵活,自定义指令适合需要复用的场景,autofocus 属性最简单但有限制。






