vue 实现获取焦点
在 Vue 中实现获取焦点
通过 ref 和 focus() 方法可以手动触发元素的焦点。在 Vue 模板中为需要获取焦点的元素添加 ref 属性,然后在 JavaScript 中调用 focus()。
<template>
<input ref="inputRef" />
</template>
<script>
export default {
mounted() {
this.$refs.inputRef.focus();
}
};
</script>
使用自定义指令实现自动获取焦点
可以创建一个自定义指令 v-focus,在元素插入 DOM 时自动聚焦。
<template>
<input v-focus />
</template>
<script>
export default {
directives: {
focus: {
inserted(el) {
el.focus();
}
}
}
};
</script>
在 Vue 3 中使用 Composition API
Vue 3 的 Composition API 提供了更灵活的方式来管理焦点逻辑。
<template>
<input ref="inputRef" />
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const inputRef = ref(null);
onMounted(() => {
inputRef.value.focus();
});
return { inputRef };
}
};
</script>
动态控制焦点
通过绑定 v-if 或 v-show 结合 nextTick 确保元素渲染完成后再聚焦。
<template>
<button @click="showInput = true">显示输入框</button>
<input v-if="showInput" ref="inputRef" />
</template>
<script>
export default {
data() {
return {
showInput: false
};
},
watch: {
showInput(newVal) {
if (newVal) {
this.$nextTick(() => {
this.$refs.inputRef.focus();
});
}
}
}
};
</script>
表单验证后自动聚焦错误字段
结合表单验证库(如 VeeValidate),在验证失败时将焦点移动到第一个错误字段。

<template>
<form @submit.prevent="submitForm">
<input v-model="email" ref="emailRef" />
<input v-model="password" ref="passwordRef" />
<button type="submit">提交</button>
</form>
</template>
<script>
export default {
data() {
return {
email: '',
password: ''
};
},
methods: {
submitForm() {
if (!this.email) {
this.$refs.emailRef.focus();
return;
}
if (!this.password) {
this.$refs.passwordRef.focus();
return;
}
// 提交逻辑
}
}
};
</script>
以上方法涵盖了 Vue 中获取焦点的常见场景,可根据具体需求选择适合的方式。






