From 61e5746b0db0d5f17e0638fb081c62a7ea826682 Mon Sep 17 00:00:00 2001 From: Zev Zhu <45655660+aibayanyu20@users.noreply.github.com> Date: Tue, 17 Oct 2023 18:55:10 +0800 Subject: [PATCH] fix(StyleContext): fix style cache loaded repeat (#7029) Co-authored-by: unknown --- components/_util/cssinjs/StyleContext.tsx | 34 +++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/components/_util/cssinjs/StyleContext.tsx b/components/_util/cssinjs/StyleContext.tsx index 50189729c..faf49f4b5 100644 --- a/components/_util/cssinjs/StyleContext.tsx +++ b/components/_util/cssinjs/StyleContext.tsx @@ -1,5 +1,13 @@ import type { ShallowRef, ExtractPropTypes, InjectionKey, Ref } from 'vue'; -import { provide, defineComponent, unref, inject, watch, shallowRef } from 'vue'; +import { + provide, + defineComponent, + unref, + inject, + watch, + shallowRef, + getCurrentInstance, +} from 'vue'; import CacheEntity from './Cache'; import type { Linter } from './linters/interface'; import type { Transformer } from './transformers/interface'; @@ -80,6 +88,27 @@ const StyleContextKey: InjectionKey>> = Symbol('StyleContextKey'); export type UseStyleProviderProps = Partial | Ref>; + +// fix: https://github.com/vueComponent/ant-design-vue/issues/7023 +const getCache = () => { + const instance = getCurrentInstance(); + let cache: CacheEntity; + if (instance && instance.appContext) { + const globalCache = instance.appContext?.config?.globalProperties?.__ANTDV_CSSINJS_CACHE__; + if (globalCache) { + cache = globalCache; + } else { + cache = createCache(); + if (instance.appContext.config.globalProperties) { + instance.appContext.config.globalProperties.__ANTDV_CSSINJS_CACHE__ = cache; + } + } + } else { + cache = createCache(); + } + return cache; +}; + const defaultStyleContext: StyleContextProps = { cache: createCache(), defaultCache: true, @@ -87,7 +116,8 @@ const defaultStyleContext: StyleContextProps = { }; // fix: https://github.com/vueComponent/ant-design-vue/issues/6912 export const useStyleInject = () => { - return inject(StyleContextKey, shallowRef({ ...defaultStyleContext, cache: createCache() })); + const cache = getCache(); + return inject(StyleContextKey, shallowRef({ ...defaultStyleContext, cache })); }; export const useStyleProvider = (props: UseStyleProviderProps) => { const parentContext = useStyleInject();