Skip to content

Commit 49dc2dd

Browse files
committedJul 16, 2021
fix(sfc/style-vars): properly re-apply style vars on component root elements change
Now uses MutationObserver to ensure it works even for HOCs fix #3894
1 parent 317654b commit 49dc2dd

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed
 

‎packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts

+36-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
reactive,
88
nextTick,
99
ComponentOptions,
10-
Suspense
10+
Suspense,
11+
FunctionalComponent
1112
} from '@vue/runtime-dom'
1213

1314
describe('useCssVars', () => {
@@ -142,6 +143,40 @@ describe('useCssVars', () => {
142143
}
143144
})
144145

146+
// #3894
147+
test('with subTree change inside HOC', async () => {
148+
const state = reactive({ color: 'red' })
149+
const value = ref(true)
150+
const root = document.createElement('div')
151+
152+
const Child: FunctionalComponent = (_, { slots }) => slots.default!()
153+
154+
const App = {
155+
setup() {
156+
useCssVars(() => state)
157+
return () =>
158+
h(
159+
Child,
160+
null,
161+
() => (value.value ? [h('div')] : [h('div'), h('div')])
162+
)
163+
}
164+
}
165+
166+
render(h(App), root)
167+
await nextTick()
168+
// css vars use with fallback tree
169+
for (const c of [].slice.call(root.children as any)) {
170+
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
171+
}
172+
173+
value.value = false
174+
await nextTick()
175+
for (const c of [].slice.call(root.children as any)) {
176+
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
177+
}
178+
})
179+
145180
test('with createStaticVNode', async () => {
146181
const state = reactive({ color: 'red' })
147182
const root = document.createElement('div')

‎packages/runtime-dom/src/helpers/useCssVars.ts

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import {
22
getCurrentInstance,
3-
onMounted,
43
warn,
54
VNode,
65
Fragment,
76
Static,
8-
onUpdated,
9-
watchEffect
7+
watchPostEffect,
8+
onMounted,
9+
onUnmounted
1010
} from '@vue/runtime-core'
1111
import { ShapeFlags } from '@vue/shared'
1212

@@ -27,8 +27,12 @@ export function useCssVars(getter: (ctx: any) => Record<string, string>) {
2727

2828
const setVars = () =>
2929
setVarsOnVNode(instance.subTree, getter(instance.proxy!))
30-
onMounted(() => watchEffect(setVars, { flush: 'post' }))
31-
onUpdated(setVars)
30+
watchPostEffect(setVars)
31+
onMounted(() => {
32+
const ob = new MutationObserver(setVars)
33+
ob.observe(instance.subTree.el!.parentNode, { childList: true })
34+
onUnmounted(() => ob.disconnect())
35+
})
3236
}
3337

3438
function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {

0 commit comments

Comments
 (0)