2022-03-25 15:35:56 +08:00
|
|
|
import { computed, getCurrentInstance } from 'vue'
|
2022-02-08 10:37:21 +08:00
|
|
|
import { fromPairs } from 'lodash-unified'
|
2022-02-11 11:03:15 +08:00
|
|
|
import { debugWarn } from '@element-plus/utils'
|
2021-09-10 10:00:44 +08:00
|
|
|
|
|
|
|
import type { ComputedRef } from 'vue'
|
2020-09-19 20:44:07 +08:00
|
|
|
|
2020-12-07 10:57:48 +08:00
|
|
|
interface Params {
|
|
|
|
excludeListeners?: boolean
|
2022-05-10 21:51:17 +08:00
|
|
|
excludeKeys?: ComputedRef<string[]>
|
2020-12-07 10:57:48 +08:00
|
|
|
}
|
|
|
|
|
2020-09-19 20:44:07 +08:00
|
|
|
const DEFAULT_EXCLUDE_KEYS = ['class', 'style']
|
|
|
|
const LISTENER_PREFIX = /^on[A-Z]/
|
|
|
|
|
2021-11-29 15:58:44 +08:00
|
|
|
export const useAttrs = (
|
|
|
|
params: Params = {}
|
|
|
|
): ComputedRef<Record<string, unknown>> => {
|
2022-05-10 21:51:17 +08:00
|
|
|
const { excludeListeners = false, excludeKeys } = params
|
|
|
|
const allExcludeKeys = computed<string[]>(() => {
|
|
|
|
return (excludeKeys?.value || []).concat(DEFAULT_EXCLUDE_KEYS)
|
|
|
|
})
|
2020-09-19 20:44:07 +08:00
|
|
|
|
2021-09-10 10:00:44 +08:00
|
|
|
const instance = getCurrentInstance()
|
|
|
|
if (!instance) {
|
2021-09-10 15:00:39 +08:00
|
|
|
debugWarn(
|
2021-09-10 10:00:44 +08:00
|
|
|
'use-attrs',
|
|
|
|
'getCurrentInstance() returned null. useAttrs() must be called at the top of a setup function'
|
|
|
|
)
|
|
|
|
return computed(() => ({}))
|
|
|
|
}
|
|
|
|
|
|
|
|
return computed(() =>
|
2021-09-15 14:43:34 +08:00
|
|
|
fromPairs(
|
2021-10-06 20:17:18 +08:00
|
|
|
Object.entries(instance.proxy?.$attrs!).filter(
|
2021-09-10 10:00:44 +08:00
|
|
|
([key]) =>
|
2022-05-10 21:51:17 +08:00
|
|
|
!allExcludeKeys.value.includes(key) &&
|
2021-09-10 10:00:44 +08:00
|
|
|
!(excludeListeners && LISTENER_PREFIX.test(key))
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
2020-09-19 20:44:07 +08:00
|
|
|
}
|