vue 实现 input focus
实现 input focus 的方法
在 Vue 中实现 input 元素的 focus 可以通过多种方式完成,以下是几种常见的方法:
使用 ref 和 $refs
通过 ref 属性获取 DOM 元素,并在 mounted 或需要时调用 focus 方法。
<template>
<input ref="inputRef" />
</template>
<script>
export default {
mounted() {
this.$refs.inputRef.focus();
}
}
</script>
使用 v-focus 自定义指令
创建一个自定义指令 v-focus,自动聚焦元素。
<template>
<input v-focus />
</template>
<script>
export default {
directives: {
focus: {
inserted(el) {
el.focus();
}
}
}
}
</script>
通过 $nextTick 确保 DOM 更新
在某些情况下,可能需要等待 DOM 更新完成后再聚焦。
<template>
<input ref="inputRef" v-if="showInput" />
</template>
<script>
export default {
data() {
return {
showInput: false
};
},
methods: {
showAndFocus() {
this.showInput = true;
this.$nextTick(() => {
this.$refs.inputRef.focus();
});
}
}
}
</script>
动态绑定 focus 状态
通过绑定 :focus 属性实现动态控制。
<template>
<input :focus="isFocused" @blur="isFocused = false" />
</template>
<script>
export default {
data() {
return {
isFocused: true
};
}
}
</script>
使用第三方库
如 vue-focus 等库可以简化聚焦逻辑。
<template>
<input v-focus="true" />
</template>
<script>
import { focus } from 'vue-focus';
export default {
directives: { focus }
}
</script>
注意事项
- 确保元素在 DOM 中存在后再调用
focus方法。 - 自定义指令适用于需要复用的场景。
- 动态绑定时需处理
blur事件以避免状态不一致。







