perf: caching handlers of useRefs (#10108)

This commit is contained in:
neverland 2021-12-28 11:46:48 +08:00 committed by GitHub
parent 7e4d3da983
commit 8d60697ec1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,14 +2,20 @@ import { ref, Ref, onBeforeUpdate } from 'vue';
export function useRefs<T = Element>() { export function useRefs<T = Element>() {
const refs = ref([]) as Ref<T[]>; const refs = ref([]) as Ref<T[]>;
const cache: Array<(el: unknown) => void> = [];
onBeforeUpdate(() => { onBeforeUpdate(() => {
refs.value = []; refs.value = [];
}); });
const setRefs = (index: number) => (el: unknown) => { const setRefs = (index: number) => {
if (!cache[index]) {
cache[index] = (el: unknown) => {
refs.value[index] = el as T; refs.value[index] = el as T;
}; };
}
return cache[index];
};
return [refs, setRefs] as const; return [refs, setRefs] as const;
} }