Skip to content

useKeyModifier

反应式 修饰符状态。跟踪任何 支持的修饰符 的状态 - 请参阅浏览器兼容性说明。

¥Reactive Modifier State. Tracks state of any of the supported modifiers - see Browser Compatibility notes.

通过 Vue School 的免费视频课程学习 useKeyModifier!

示例

capsLock
numLock
scrollLock
shift
control
alt

用法

¥Usage

ts
import { useKeyModifier } from '@vueuse/core'

const capsLockState = useKeyModifier('CapsLock')

console.log(capsLockState.value)

活动

¥Events

你可以自定义哪些事件将提示状态更新。默认情况下,这些是 mouseupmousedownkeyupkeydown。要自定义这些事件:

¥You can customize which events will prompt the state to update. By default, these are mouseup, mousedown, keyup, keydown. To customize these events:

ts
import { useKeyModifier } from '@vueuse/core'

const capsLockState = useKeyModifier('CapsLock', { events: ['mouseup', 'mousedown'] })

console.log(capsLockState) // null

// Caps Lock turned on with key press
console.log(capsLockState) // null

// Mouse button clicked
console.log(capsLockState) // true

初始状态

¥Initial State

默认情况下,返回的 ref 将为 Ref<null>,直到收到第一个事件。你可以通过以下方式显式地将初始状态传递给它:

¥By default, the returned ref will be Ref<null> until the first event is received. You can explicitly pass the initial state to it via:

ts
const capsLockState1 = useKeyModifier('CapsLock') // Ref<boolean | null>
const capsLockState2 = useKeyModifier('CapsLock', { initial: false }) // Ref<boolean>

类型声明

typescript
export type KeyModifier =
  | "Alt"
  | "AltGraph"
  | "CapsLock"
  | "Control"
  | "Fn"
  | "FnLock"
  | "Meta"
  | "NumLock"
  | "ScrollLock"
  | "Shift"
  | "Symbol"
  | "SymbolLock"
export interface UseModifierOptions<Initial> extends ConfigurableDocument {
  /**
   * Event names that will prompt update to modifier states
   *
   * @default ['mousedown', 'mouseup', 'keydown', 'keyup']
   */
  events?: WindowEventName[]
  /**
   * Initial value of the returned ref
   *
   * @default null
   */
  initial?: Initial
}
export type UseKeyModifierReturn<Initial> = Ref<
  Initial extends boolean ? boolean : boolean | null
>
export declare function useKeyModifier<Initial extends boolean | null>(
  modifier: KeyModifier,
  options?: UseModifierOptions<Initial>,
): UseKeyModifierReturn<Initial>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号