Skip to content

Commit f4a753a

Browse files
committed
fix(theme-provider): reactive theme loss issue (#15)
1 parent 9ce5920 commit f4a753a

File tree

3 files changed

+31
-12
lines changed

3 files changed

+31
-12
lines changed

core/providers/theme.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1-
import { defineComponent, h, PropType, provide } from 'vue'
1+
import { defineComponent, h, PropType, provide, ref, watch } from 'vue'
22

33
export const ThemeProvider = defineComponent(
44
(props, { slots }) => {
5-
provide('$theme', props.theme)
5+
const theme = ref(props.theme)
6+
provide('$theme', theme)
7+
8+
watch(
9+
() => props.theme,
10+
(v) => {
11+
theme.value = v
12+
},
13+
{
14+
deep: true,
15+
},
16+
)
17+
618
return () => {
719
return h('div', null, slots)
820
}

core/styled.ts

+16-10
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
onUnmounted,
88
PropType,
99
PublicProps,
10-
reactive,
10+
Ref,
1111
SlotsType,
1212
watch,
1313
} from 'vue'
@@ -65,21 +65,27 @@ function baseStyled(target: string | InstanceType<any>, propsDefinition: Record<
6565
return defineComponent(
6666
(props, { slots }) => {
6767
const myAttrs = { ...attributes }
68-
const theme = reactive(inject<Record<string, string | number>>('$theme', {}))
68+
const theme = inject<Ref<Record<string, string | number>>>('$theme')
6969
let context = {
70-
theme,
70+
theme: theme?.value ?? {},
7171
...props,
7272
}
7373

7474
myAttrs.class = generateClassName()
7575

76-
watch([theme, props], () => {
77-
context = {
78-
theme,
79-
...props,
80-
}
81-
injectStyle<T>(myAttrs.class, cssWithExpression, context)
82-
})
76+
watch(
77+
[theme, props],
78+
() => {
79+
context = {
80+
theme: theme?.value ?? {},
81+
...props,
82+
}
83+
injectStyle<T>(myAttrs.class, cssWithExpression, context)
84+
},
85+
{
86+
deep: true,
87+
},
88+
)
8389

8490
onMounted(() => {
8591
injectStyle<T>(myAttrs.class, cssWithExpression, context)

tsconfig.json

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{
22
"compilerOptions": {
3+
"jsx": "preserve",
34
// 目标 ECMAScript 版本
45
"target": "esnext",
56
// 模块解析策略

0 commit comments

Comments
 (0)