Skip to content

Commit

Permalink
fix(useFocus): listen focus and blur to the targetElement (#2631)
Browse files Browse the repository at this point in the history
* refactor(useFocus): listen to the targetElement.

fix: #2628

* fix: initial focus

* perf: reduce judgment

* perf: simple read variable
  • Loading branch information
okxiaoliang4 committed Jan 29, 2023
1 parent 8ee7d3c commit 7cd889a
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions packages/core/useFocus/index.ts
@@ -1,10 +1,9 @@
import type { Ref } from 'vue-demi'
import { computed, watch } from 'vue-demi'
import { isDef } from '@vueuse/shared'
import { computed, ref, watch } from 'vue-demi'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
import { useActiveElement } from '../useActiveElement'
import type { ConfigurableWindow } from '../_configurable'
import { useEventListener } from '../useEventListener'

export interface UseFocusOptions extends ConfigurableWindow {
/**
Expand Down Expand Up @@ -33,16 +32,18 @@ export interface UseFocusReturn {
export function useFocus(target: MaybeElementRef, options: UseFocusOptions = {}): UseFocusReturn {
const { initialValue = false } = options

const activeElement = useActiveElement(options)
const innerFocused = ref(false)
const targetElement = computed(() => unrefElement(target))

useEventListener(targetElement, 'focus', () => innerFocused.value = true)
useEventListener(targetElement, 'blur', () => innerFocused.value = false)

const focused = computed({
get() {
return isDef(activeElement.value) && isDef(targetElement.value) && activeElement.value === targetElement.value
},
get: () => innerFocused.value,
set(value: boolean) {
if (!value && focused.value)
if (!value && innerFocused.value)
targetElement.value?.blur()
if (value && !focused.value)
else if (value && !innerFocused.value)
targetElement.value?.focus()
},
})
Expand Down

0 comments on commit 7cd889a

Please sign in to comment.