From 29f02b9cb85b0bf311e277fe8681e4dcbde91206 Mon Sep 17 00:00:00 2001 From: Akino Date: Mon, 22 Jul 2024 10:48:43 +0800 Subject: [PATCH] fix(theme-provider): reactive theme loss issue (#15) --- core/providers/theme.ts | 16 ++++++++++++++-- core/styled.ts | 26 ++++++++++++++++---------- tsconfig.json | 1 + 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/core/providers/theme.ts b/core/providers/theme.ts index c55f82a..d7f745b 100644 --- a/core/providers/theme.ts +++ b/core/providers/theme.ts @@ -1,8 +1,20 @@ -import { defineComponent, h, PropType, provide } from 'vue' +import { defineComponent, h, PropType, provide, ref, watch } from 'vue' export const ThemeProvider = defineComponent( (props, { slots }) => { - provide('$theme', props.theme) + const theme = ref(props.theme) + provide('$theme', theme) + + watch( + () => props.theme, + (v) => { + theme.value = v + }, + { + deep: true, + }, + ) + return () => { return h('div', null, slots) } diff --git a/core/styled.ts b/core/styled.ts index 44e54cf..c4ec66d 100644 --- a/core/styled.ts +++ b/core/styled.ts @@ -7,7 +7,7 @@ import { onUnmounted, PropType, PublicProps, - reactive, + Ref, SlotsType, watch, } from 'vue' @@ -65,21 +65,27 @@ function baseStyled(target: string | InstanceType, propsDefinition: Record< return defineComponent( (props, { slots }) => { const myAttrs = { ...attributes } - const theme = reactive(inject>('$theme', {})) + const theme = inject>>('$theme') let context = { - theme, + theme: theme?.value ?? {}, ...props, } myAttrs.class = generateClassName() - watch([theme, props], () => { - context = { - theme, - ...props, - } - injectStyle(myAttrs.class, cssWithExpression, context) - }) + watch( + [theme, props], + () => { + context = { + theme: theme?.value ?? {}, + ...props, + } + injectStyle(myAttrs.class, cssWithExpression, context) + }, + { + deep: true, + }, + ) onMounted(() => { injectStyle(myAttrs.class, cssWithExpression, context) diff --git a/tsconfig.json b/tsconfig.json index 635277e..9a2f285 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { + "jsx": "preserve", // 目标 ECMAScript 版本 "target": "esnext", // 模块解析策略