]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(runtime-dom): set css vars before user onMounted hooks
authorEvan You <evan@vuejs.org>
Thu, 14 Nov 2024 07:49:39 +0000 (15:49 +0800)
committerEvan You <evan@vuejs.org>
Thu, 14 Nov 2024 07:50:19 +0000 (15:50 +0800)
close #11533

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

index c4df0873140b8ad67b5259c851a792f883bf8285..acba3315862a4d480c109cc5ea615935167ca46c 100644 (file)
@@ -7,6 +7,7 @@ import {
   defineCustomElement,
   h,
   nextTick,
+  onMounted,
   reactive,
   ref,
   render,
@@ -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`)
+  })
 })
index e57705304bfe679b106dab258e04251d1ecb24b2..6331208c5c0e5dea22d7328d3464fc692fc5b026 100644 (file)
@@ -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' : '')
 /**
@@ -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())