feat: 添加 defineOptions

This commit is contained in:
vben
2023-04-06 00:08:17 +08:00
parent 8e5a6b7ce5
commit 5e8ef2f64f
25 changed files with 346 additions and 159 deletions

View File

@@ -1,2 +1,2 @@
// life-cycle
export * from './lifecycle/onMountedOrActivated';
export * from './onMountedOrActivated';
export * from './useAttrs';

View File

@@ -0,0 +1,43 @@
import { getCurrentInstance, reactive, shallowRef, watchEffect } from 'vue';
import { type Recordable } from '@vben/types';
interface Options {
excludeListeners?: boolean;
excludeKeys?: string[];
excludeDefaultKeys?: boolean;
}
const DEFAULT_EXCLUDE_KEYS = ['class', 'style'];
const LISTENER_PREFIX = /^on[A-Z]/;
function entries<T>(obj: Recordable<T>): [string, T][] {
return Object.keys(obj).map((key: string) => [key, obj[key]]);
}
function useAttrs(options: Options = {}): Recordable<any> {
const instance = getCurrentInstance();
if (!instance) return {};
const { excludeListeners = false, excludeKeys = [], excludeDefaultKeys = true } = options;
const attrs = shallowRef({});
const allExcludeKeys = excludeKeys.concat(excludeDefaultKeys ? 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 Recordable<any>);
attrs.value = res;
});
return attrs;
}
export { useAttrs };