index.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { computed, getCurrentInstance } from 'vue'
  2. import { fromPairs } from 'lodash-unified'
  3. import { debugWarn } from '@element-plus/utils'
  4. import type { ComputedRef } from 'vue'
  5. interface Params {
  6. excludeListeners?: boolean
  7. excludeKeys?: ComputedRef<string[]>
  8. }
  9. const DEFAULT_EXCLUDE_KEYS = ['class', 'style']
  10. const LISTENER_PREFIX = /^on[A-Z]/
  11. export const useAttrs = (
  12. params: Params = {}
  13. ): ComputedRef<Record<string, unknown>> => {
  14. const { excludeListeners = false, excludeKeys } = params
  15. const allExcludeKeys = computed<string[]>(() => {
  16. return (excludeKeys?.value || []).concat(DEFAULT_EXCLUDE_KEYS)
  17. })
  18. const instance = getCurrentInstance()
  19. if (!instance) {
  20. debugWarn(
  21. 'use-attrs',
  22. 'getCurrentInstance() returned null. useAttrs() must be called at the top of a setup function'
  23. )
  24. return computed(() => ({}))
  25. }
  26. return computed(() =>
  27. fromPairs(
  28. Object.entries(instance.proxy?.$attrs!).filter(
  29. ([key]) =>
  30. !allExcludeKeys.value.includes(key) &&
  31. !(excludeListeners && LISTENER_PREFIX.test(key))
  32. )
  33. )
  34. )
  35. }