跳到內容

useFocusWithin

Category
匯出大小
1.13 kB
Last Changed
3 週前

追蹤元素或其後代是否具有焦點的響應式工具。它旨在匹配 :focus-within CSS 偽類別的行為。常見的用例是在表單元素上查看其任何輸入目前是否具有焦點。

Demo

表單中的焦點:false

基本用法

vue
<script>
import { useFocusWithin } from '@vueuse/core'

const target = ref()
const { focused } = useFocusWithin(target)

watch(focused, (focused) => {
  if (focused)
    console.log('Target contains the focused element')
  else console.log('Target does NOT contain the focused element')
})
</script>

<template>
  <form ref="target">
    <input type="text" placeholder="First Name">
    <input type="text" placeholder="Last Name">
    <input type="text" placeholder="Email">
    <input type="text" placeholder="Password">
  </form>
</template>

類型宣告

typescript
export interface UseFocusWithinReturn {
  /**
   * True if the element or any of its descendants are focused
   */
  focused: ComputedRef<boolean>
}
/**
 * Track if focus is contained within the target element
 *
 * @see https://vueuse.dev.org.tw/useFocusWithin
 * @param target The target element to track
 * @param options Focus within options
 */
export declare function useFocusWithin(
  target: MaybeElementRef,
  options?: ConfigurableWindow,
): UseFocusWithinReturn

原始碼

SourceDemoDocs

貢獻者

Anthony Fu
Anthony Fu
Ben Lau
IlyaL
Fernando Fernández
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

更新日誌

v12.4.0 於 2025/1/10
dd316 - feat: 盡可能在所有地方使用被動事件處理器 (#4477)
v12.3.0 於 2025/1/2
3ca0d - fix: 正確追蹤在同一個容器中切換元素焦點時的狀態 (#4394)
v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理 (#4349)
v11.1.0 於 2024/9/16
c5407 - fix: 使 useFocusWhithin 符合 :focus-within 的行為 (#4134)
v10.0.0-beta.3 於 2023/4/12
e75a5 - feat: 更新依賴

在 MIT 許可證下發布。