Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useActiveElement): use computedWithControl instead of counter ref #2093

Merged
merged 3 commits into from Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 8 additions & 9 deletions packages/core/useActiveElement/index.ts
@@ -1,4 +1,4 @@
import { computed, ref } from 'vue-demi'
import { computedWithControl } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
Expand All @@ -11,16 +11,15 @@ import { defaultWindow } from '../_configurable'
*/
export function useActiveElement<T extends HTMLElement>(options: ConfigurableWindow = {}) {
const { window = defaultWindow } = options
const counter = ref(0)
const activeElement = computedWithControl(
() => null,
() => window?.document.activeElement as T | null | undefined,
)

if (window) {
useEventListener(window, 'blur', () => counter.value += 1, true)
useEventListener(window, 'focus', () => counter.value += 1, true)
useEventListener(window, 'blur', activeElement.trigger, true)
useEventListener(window, 'focus', activeElement.trigger, true)
}

return computed(() => {
// eslint-disable-next-line no-unused-expressions
counter.value
return window?.document.activeElement as T | null | undefined
})
return activeElement
}
25 changes: 11 additions & 14 deletions packages/core/useCurrentElement/index.ts
@@ -1,19 +1,16 @@
// eslint-disable-next-line no-restricted-imports
import { computed, getCurrentInstance, onMounted, onUpdated, ref } from 'vue-demi'
import { getCurrentInstance, onMounted, onUpdated } from 'vue-demi'
import { computedWithControl } from '@vueuse/shared'

export function useCurrentElement<T extends Element = Element>() {
const vm = getCurrentInstance()!
const count = ref(0)
onUpdated(() => {
count.value += 1
})
onMounted(() => {
count.value += 1
})
return computed<T>(() => {
// force update
// eslint-disable-next-line no-unused-expressions
count.value
return vm.proxy!.$el
})
const currentElement = computedWithControl(
() => null,
() => vm.proxy!.$el as T,
)

onUpdated(currentElement.trigger)
onMounted(currentElement.trigger)

return currentElement
}