backdrop
工具

焦点范围(Focus Scope)

在组件边界内管理焦点,支持捕获和循环焦点导航。

焦点范围(Focus Scope)提供了在组件边界内对键盘焦点管理的增强控制。它可以捕获焦点到其容器内,并可选择循环焦点导航,使其成为模态界面和其他需要管理焦点状态的交互组件的理想选择。

API 参考

PropDefaultType
as
'div'
AsTag | Component

The element or component this component should render as. Can be overwritten by asChild.

asChild
boolean

Change the default rendered element for the one passed as a child, merging their props and behavior.

Read our Composition guide for more details.

loop
false
boolean

When true, tabbing from last item will focus first tabbable and shift+tab from first item will focus last tababble.

trapped
false
boolean

When true, focus cannot escape the focus scope via keyboard, pointer, or a programmatic focus.

EmitPayload
mountAutoFocus
[event: Event]

Event handler called when auto-focusing on mount. Can be prevented.

unmountAutoFocus
[event: Event]

Event handler called when auto-focusing on unmount. Can be prevented.

示例

基础用法(含焦点捕获)

vue
<template>
  <FocusScope :trapped="true">
    <div>
      <button>操作 1</button>
      <button>操作 2</button>
      <button>关闭</button>
    </div>
  </FocusScope>
</template>

带焦点循环

同时启用捕获和循环以实现完整的焦点管理:

vue
<template>
  <FocusScope :trapped="true" :loop="true">
    <div>
      <button v-for="item in items" :key="item.id">
        {{ item.label }}
      </button>
    </div>
  </FocusScope>
</template>

处理焦点事件

vue
<script setup>
function handleMountFocus(event) {
  // 根据需要阻止默认的自动聚焦行为
  event.preventDefault()
}
</script>

<template>
  <FocusScope
    @mount-auto-focus="handleMountFocus"
    @unmount-auto-focus="handleUnmountFocus"
  >
    <div>

    </div>
  </FocusScope>
</template>

warning

使用捕获模式时,请确保范围内始终至少存在一个可聚焦元素,以防止焦点被捕获到无法访问的状态。