Skip to content

useActiveElement

类别
导出大小
1.18 kB
最近修改
2 days ago

响应式 document.activeElement。返回一个在焦点变化时更新的浅层 ref。

🌐 Reactive document.activeElement. Returns a shallow ref that updates when focus changes.

示例

Select the inputs below to see the changes
Current Active Element: null

用法

🌐 Usage

vue
<script setup lang="ts">
import { 
useActiveElement
} from '@vueuse/core'
import {
watch
} from 'vue'
const
activeElement
=
useActiveElement
()
watch
(
activeElement
, (
el
) => {
console
.
log
('focus changed to',
el
)
}) </script>

影子 DOM 支持

🌐 Shadow DOM Support

默认情况下,useActiveElement 会遍历 shadow DOM 以查找深层活动元素。设置 deep: false 可禁用此行为。

🌐 By default, useActiveElement will traverse into shadow DOM to find the deeply active element. Set deep: false to disable this behavior.

ts
import { 
useActiveElement
} from '@vueuse/core'
// Only get the shadow host, not the element inside shadow DOM const
activeElement
=
useActiveElement
({
deep
: false })

追踪元素移除

🌐 Track Element Removal

triggerOnRemoval: true 设置为在当前活动元素从 DOM 中移除时更新活动元素。这在底层使用了一个 MutationObserver

🌐 Set triggerOnRemoval: true to update the active element when the currently active element is removed from the DOM. This uses a MutationObserver under the hood.

ts
import { 
useActiveElement
} from '@vueuse/core'
const
activeElement
=
useActiveElement
({
triggerOnRemoval
: true })

组件用法

🌐 Component Usage

vue
<template>
  <UseActiveElement v-slot="{ 
element
}">
Active element is {{
element
?.dataset.id }}
</UseActiveElement> </template>