vue-vben-admin/packages/hooks/src/useAttrs.ts

44 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-04-06 00:08:17 +08:00
import { type Recordable } from '@vben/types';
2023-04-06 23:28:37 +08:00
import { getCurrentInstance, reactive, shallowRef, watchEffect } from 'vue';
2023-04-05 22:47:14 +08:00
interface UseAttrsOptions {
2020-12-25 01:09:44 +08:00
excludeListeners?: boolean;
excludeKeys?: string[];
excludeDefaultKeys?: boolean;
2020-12-25 01:09:44 +08:00
}
const DEFAULT_EXCLUDE_KEYS = ['class', 'style'];
const LISTENER_PREFIX = /^on[A-Z]/;
2023-04-06 00:08:17 +08:00
function entries<T>(obj: Recordable<T>): [string, T][] {
2020-12-25 01:09:44 +08:00
return Object.keys(obj).map((key: string) => [key, obj[key]]);
}
function useAttrs(options: UseAttrsOptions = {}): Recordable<any> {
2020-12-25 01:09:44 +08:00
const instance = getCurrentInstance();
if (!instance) return {};
2023-04-06 00:08:17 +08:00
const { excludeListeners = false, excludeKeys = [], excludeDefaultKeys = true } = options;
2020-12-25 01:09:44 +08:00
const attrs = shallowRef({});
const allExcludeKeys = excludeKeys.concat(excludeDefaultKeys ? DEFAULT_EXCLUDE_KEYS : []);
2020-12-25 01:09:44 +08:00
// Since attrs are not reactive, make it reactive instead of doing in `onUpdated` hook for better performance
instance.attrs = reactive(instance.attrs);
watchEffect(() => {
const res = entries(instance.attrs).reduce((acm, [key, val]) => {
if (!allExcludeKeys.includes(key) && !(excludeListeners && LISTENER_PREFIX.test(key))) {
acm[key] = val;
}
return acm;
2023-04-06 00:08:17 +08:00
}, {} as Recordable<any>);
2020-12-25 01:09:44 +08:00
attrs.value = res;
});
return attrs;
}
2023-04-06 00:08:17 +08:00
export { useAttrs, type UseAttrsOptions };