Skip to content

Commit 2d5c5e2

Browse files
committedNov 14, 2024··
fix(runtime-dom): set css vars before user onMounted hooks
close #11533
1 parent 99009ee commit 2d5c5e2

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed
 

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

+22
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
defineCustomElement,
88
h,
99
nextTick,
10+
onMounted,
1011
reactive,
1112
ref,
1213
render,
@@ -405,4 +406,25 @@ describe('useCssVars', () => {
405406
`<css-vars-ce style="--color: red;"></css-vars-ce>`,
406407
)
407408
})
409+
410+
test('should set vars before child component onMount hook', () => {
411+
const state = reactive({ color: 'red' })
412+
const root = document.createElement('div')
413+
let colorInOnMount
414+
415+
const App = {
416+
setup() {
417+
useCssVars(() => state)
418+
onMounted(() => {
419+
colorInOnMount = (
420+
root.children[0] as HTMLElement
421+
).style.getPropertyValue(`--color`)
422+
})
423+
return () => h('div')
424+
},
425+
}
426+
427+
render(h(App), root)
428+
expect(colorInOnMount).toBe(`red`)
429+
})
408430
})

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

+4-7
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ import {
33
Static,
44
type VNode,
55
getCurrentInstance,
6-
onBeforeMount,
76
onMounted,
87
onUnmounted,
98
warn,
10-
watchPostEffect,
9+
watch,
1110
} from '@vue/runtime-core'
12-
import { ShapeFlags } from '@vue/shared'
11+
import { NOOP, ShapeFlags } from '@vue/shared'
1312

1413
export const CSS_VAR_TEXT: unique symbol = Symbol(__DEV__ ? 'CSS_VAR_TEXT' : '')
1514
/**
@@ -48,11 +47,9 @@ export function useCssVars(getter: (ctx: any) => Record<string, string>): void {
4847
updateTeleports(vars)
4948
}
5049

51-
onBeforeMount(() => {
52-
watchPostEffect(setVars)
53-
})
54-
5550
onMounted(() => {
51+
// run setVars synchronously here, but run as post-effect on changes
52+
watch(setVars, NOOP, { flush: 'post' })
5653
const ob = new MutationObserver(setVars)
5754
ob.observe(instance.subTree.el!.parentNode, { childList: true })
5855
onUnmounted(() => ob.disconnect())

0 commit comments

Comments
 (0)
Please sign in to comment.