Appearance
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)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| delay | number | 0 | 延迟聚焦的毫秒数 |
| select | boolean | false | 聚焦后选中文本 |
| enabled | boolean | true | 是否启用指令 |
| preventScroll | boolean | false | 是否阻止滚动到聚焦元素 |
| setTabIndexIfNeeded | boolean | true | 当元素不可聚焦时设置 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')