123456789101112131415161718192021222324252627282930313233343536373839 |
- import { getCurrentInstance, reactive, shallowRef, watchEffect } from 'vue';
- interface Params {
- excludeListeners?: boolean;
- excludeKeys?: string[];
- }
- const DEFAULT_EXCLUDE_KEYS = ['class', 'style'];
- const LISTENER_PREFIX = /^on[A-Z]/;
- export function entries<T>(obj: Hash<T>): [string, T][] {
- return Object.keys(obj).map((key: string) => [key, obj[key]]);
- }
- export function useAttrs(params: Params = {}) {
- const instance = getCurrentInstance();
- if (!instance) return {};
- const { excludeListeners = false, excludeKeys = [] } = params;
- const attrs = shallowRef({});
- const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS);
- // 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;
- }, {} as Hash<any>);
- attrs.value = res;
- });
- return attrs;
- }
|