Skip to content

Commit

Permalink
fix(useActiveElement): use computedWithControl instead of counter
Browse files Browse the repository at this point in the history
… ref (#2093)
  • Loading branch information
vaakian committed Aug 23, 2022
1 parent 1eb83c4 commit c534e43
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 23 deletions.
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
}

0 comments on commit c534e43

Please sign in to comment.