Skip to content

Commit

Permalink
fix(runtime-dom): set css vars before user onMounted hooks
Browse files Browse the repository at this point in the history
close #11533
  • Loading branch information
yyx990803 committed Nov 14, 2024
1 parent 99009ee commit 2d5c5e2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
22 changes: 22 additions & 0 deletions packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
defineCustomElement,
h,
nextTick,
onMounted,
reactive,
ref,
render,
Expand Down Expand Up @@ -405,4 +406,25 @@ describe('useCssVars', () => {
`<css-vars-ce style="--color: red;"></css-vars-ce>`,
)
})

test('should set vars before child component onMount hook', () => {
const state = reactive({ color: 'red' })
const root = document.createElement('div')
let colorInOnMount

const App = {
setup() {
useCssVars(() => state)
onMounted(() => {
colorInOnMount = (
root.children[0] as HTMLElement
).style.getPropertyValue(`--color`)
})
return () => h('div')
},
}

render(h(App), root)
expect(colorInOnMount).toBe(`red`)
})
})
11 changes: 4 additions & 7 deletions packages/runtime-dom/src/helpers/useCssVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import {
Static,
type VNode,
getCurrentInstance,
onBeforeMount,
onMounted,
onUnmounted,
warn,
watchPostEffect,
watch,
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared'
import { NOOP, ShapeFlags } from '@vue/shared'

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

onBeforeMount(() => {
watchPostEffect(setVars)
})

onMounted(() => {
// run setVars synchronously here, but run as post-effect on changes
watch(setVars, NOOP, { flush: 'post' })
const ob = new MutationObserver(setVars)
ob.observe(instance.subTree.el!.parentNode, { childList: true })
onUnmounted(() => ob.disconnect())
Expand Down

0 comments on commit 2d5c5e2

Please sign in to comment.