Skip to content

onStartTyping

类别
导出体积
772 B
上次更改
7 minutes ago

当用户在不可编辑的元素上开始输入时触发。用于当用户在页面任意位置开始输入时,自动聚焦输入框。

示例

输入任何内容

用法

vue
<script setup lang="ts">
import { 
onStartTyping
} from '@vueuse/core'
import {
useTemplateRef
} from 'vue'
const
input
=
useTemplateRef
('input')
onStartTyping
(() => {
if (!
input
.
value
.active)
input
.
value
.
focus
()
}) </script> <template> <
input
ref
="
input
"
type
="text"
placeholder
="开始输入以聚焦">
</template>

自定义有效键

ts
import { 
onStartTyping
} from '@vueuse/core'
onStartTyping
(handleKey, {
// only allow numbers
isTypedCharValid
:
e
=> /^\d$/.
test
(
e
.
key
)
})

自定义可编辑元素

ts
import { 
isFocusedElementEditable
as
defaultEditable
,
onStartTyping
} from '@vueuse/core'
onStartTyping
(handleKey, {
isFocusedElementEditable
: () => {
const {
activeElement
} =
document
// Exclude elements with id 'targetInput' if (
activeElement
?.
id
=== 'targetInput')
return true return
defaultEditable
()
} })

工作原理

回调函数仅在以下情况下触发:

  • 没有可编辑元素(<input><textarea>contenteditable)被聚焦
  • 按下的键是字母数字键(A-Z,0-9)
  • 未按下任何修饰键(Ctrl、Alt、Meta)

这样,用户就可以在页面的任何位置开始输入,而不会在使用键盘快捷键或与表单字段交互时意外触发回调。

isFocusedElementEditableisTypedCharValid 也都作为工具函数导出,因此你可以在编写自定义选项时复用它们。

类型声明

ts
export declare function 
isFocusedElementEditable
(): boolean
export declare function
isTypedCharValid
({
keyCode
,
metaKey
,
ctrlKey
,
altKey
,
}: KeyboardEvent): boolean export interface OnStartTypingOptions extends ConfigurableDocument {
isTypedCharValid
?: (
event
: KeyboardEvent) => boolean
isFocusedElementEditable
?: () => boolean
} /** * 用户在不可编辑的元素上开始输入时触发回调。 * * @see https://vueuse.org/onStartTyping * @param callback * @param options */ export declare function
onStartTyping
(
callback
: (
event
: KeyboardEvent) => void,
options
?: OnStartTypingOptions,
): void

源码

源码演示文档

贡献者

Anthony Fu
ikxin
Anthony Fu
Robin
Light_Quanta
Vida Xie
SerKo
Bernard Borg
meenie-net
丶远方
Alex Kozack
Nurettin Kaya
Antério Vieira
Seifeldin Mahjoub

更新日志

Pending for release...
1f2b7 - feat: add more configurable options for onStartTyping (#5395)
58a3b - fix: Incorrect accepted valid characters (#4616)
fccf2 - feat: upgrade deps (#3614)