Skip to content

Commit

Permalink
feat: 添加useAttrs钩子以处理Vue组件属性
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyunhe committed Oct 17, 2024
1 parent ca477e0 commit cdcf547
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './useAria'
export * from './useAttrs'
export * from './useClickOutside'
export * from './useDeprecated'
export * from './useEventListener'
Expand Down
38 changes: 38 additions & 0 deletions src/hooks/useAttrs.ts
Original file line number Diff line number Diff line change
@@ -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<string[]>
}

const DEFAULT_EXCLUDE_KEYS = ['class', 'style']
const LISTENER_PREFIX = /^on[A-Z]/

export const useAttrs = (params: Params = {}): ComputedRef<Record<string, unknown>> => {
const { excludeListeners = false, excludeKeys } = params
const allExcludeKeys = computed<string[]>(() => {
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))
)
)
)
}

0 comments on commit cdcf547

Please sign in to comment.