主题
onStartTyping
当用户在不可编辑的元素上开始输入时触发。当用户在页面上的任何地方开始输入时,这对于自动聚焦输入字段非常有用。
🌐 Fires when users start typing on non-editable elements. Useful for auto-focusing an input field when the user starts typing anywhere on the page.
示例
用法
🌐 Usage
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="Start typing to focus">
</template>自定义有效密钥
🌐 Custom Valid Key
ts
import { onStartTyping } from '@vueuse/core'
onStartTyping(handleKey, {
// only allow numbers
isTypedCharValid: e => /^\d$/.test(e.key)
})自定义可编辑元素
🌐 Custom Editable Element
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()
}
})工作原理
🌐 How It Works
回调仅在以下情况下触发:
🌐 The callback only fires when:
- 没有可编辑的元素(
<input>、<textarea>或contenteditable)被选中 - 按下的键是字母数字键(A-Z,0-9)
- 没有按下任何修饰键(Ctrl、Alt、Meta)
这允许用户在页面上的任何位置开始输入,而不会在使用键盘快捷键或与表单字段交互时意外触发回调。
🌐 This allows users to start typing anywhere on the page without accidentally triggering the callback when using keyboard shortcuts or interacting with form fields.
isFocusedElementEditable 和 isTypedCharValid 也被导出为工具函数,因此在编写自定义选项时可以重用它们。
🌐 Both isFocusedElementEditable and isTypedCharValid are also exported as utility functions, so you can reuse them when writing custom options.