Skip to content

focus 自动聚焦指令

在元素挂载或配置变化时自动聚焦,支持延迟、选择内容、阻止滚动等高级选项。智能识别组件内部的可聚焦元素。

安装与引入

按需导入(推荐)

ts
import { VFocus } from '@cuixingjian/cui-utils'

全局注册

ts
import { createApp } from 'vue'
import { VFocus } from '@cuixingjian/cui-utils'

const app = createApp(App)
app.directive('focus', VFocus)
app.mount('#app')

局部注册

vue
<script setup lang="ts">
import { VFocus as vFocus } from '@cuixingjian/cui-utils'
</script>

<template>
  <input v-focus="true" />
</template>

效果演示

交互式演示

点击按钮触发输入框聚焦。

使用代码

基本用法:

vue
<template>
  <input v-focus="true" placeholder="自动聚焦" />
</template>

延迟聚焦:

vue
<template>
  <input v-focus="{ delay: 300 }" placeholder="300ms后聚焦" />
</template>

选中文本:

vue
<template>
  <input v-focus="{ select: true }" value="会被选中的文本" />
</template>

组合选项:

vue
<template>
  <input v-focus="{ delay: 200, select: true, preventScroll: true }" />
</template>

API 说明

指令值类型

类型说明示例
boolean启用/禁用聚焦v-focus="true"
Object传入配置对象v-focus="{ delay: 300 }"

配置选项 (AutoFocusOptions)

参数类型默认值说明
delaynumber0延迟聚焦的毫秒数
selectbooleanfalse聚焦后选中文本
enabledbooleantrue是否启用指令
preventScrollbooleanfalse是否阻止滚动到聚焦元素
setTabIndexIfNeededbooleantrue当元素不可聚焦时设置 tabindex
onFocus(el: Element) => void聚焦成功回调
onError(el: Element, error: any) => void聚焦失败回调

注意事项

智能聚焦

指令会自动查找组件内部的可聚焦元素:

  • <input> / <textarea> / <select> / <button>
  • [contenteditable="true"]
  • 带有 tabindex 的元素

触发时机

  • 元素挂载时:首次渲染到 DOM
  • 配置变化时:绑定值发生变化
  • 使用 :key:强制重新挂载触发聚焦

常见场景

  • 对话框打开时聚焦:使用 enabled 选项
  • 表单验证失败:使用 :key 重新聚焦
  • 动画完成后聚焦:使用 delay 选项

最佳实践

  • 延迟时间建议不超过 500ms
  • disabled 元素无法聚焦
  • 隐藏元素可能聚焦失败

源码展示

展开查看完整源码
ts
import type { Directive } from 'vue'
import { withInstallDirective } from '../install'

export interface AutoFocusOptions {
  delay?: number
  select?: boolean
  enabled?: boolean
  setTabIndexIfNeeded?: boolean
  preventScroll?: boolean
  onFocus?: (el: Element) => void
  onError?: (el: Element, error: any) => void
}

// 详见 packages/utils/directives/focus.ts
export const VFocus = withInstallDirective(focus, 'focus')