From cdcf5471780adcb733c04d35592186eddfa096df Mon Sep 17 00:00:00 2001 From: liuyunhe Date: Thu, 17 Oct 2024 09:05:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0useAttrs=E9=92=A9?= =?UTF-8?q?=E5=AD=90=E4=BB=A5=E5=A4=84=E7=90=86Vue=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/index.ts | 1 + src/hooks/useAttrs.ts | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/hooks/useAttrs.ts diff --git a/src/hooks/index.ts b/src/hooks/index.ts index c7fcd79..10be352 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,4 +1,5 @@ export * from './useAria' +export * from './useAttrs' export * from './useClickOutside' export * from './useDeprecated' export * from './useEventListener' diff --git a/src/hooks/useAttrs.ts b/src/hooks/useAttrs.ts new file mode 100644 index 0000000..b37d0c1 --- /dev/null +++ b/src/hooks/useAttrs.ts @@ -0,0 +1,38 @@ +import { computed, getCurrentInstance } from 'vue' +import { fromPairs } from 'lodash-unified' +import { debugWarn } from '@/utils' + +import type { ComputedRef } from 'vue' + +interface Params { + excludeListeners?: boolean + excludeKeys?: ComputedRef +} + +const DEFAULT_EXCLUDE_KEYS = ['class', 'style'] +const LISTENER_PREFIX = /^on[A-Z]/ + +export const useAttrs = (params: Params = {}): ComputedRef> => { + const { excludeListeners = false, excludeKeys } = params + const allExcludeKeys = computed(() => { + return (excludeKeys?.value || []).concat(DEFAULT_EXCLUDE_KEYS) + }) + + const instance = getCurrentInstance() + if (!instance) { + debugWarn( + 'use-attrs', + 'getCurrentInstance() returned null. useAttrs() must be called at the top of a setup function' + ) + return computed(() => ({})) + } + + return computed(() => + fromPairs( + Object.entries(instance.proxy?.$attrs!).filter( + ([key]) => + !allExcludeKeys.value.includes(key) && !(excludeListeners && LISTENER_PREFIX.test(key)) + ) + ) + ) +}