]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(sfc/style-vars): properly re-apply style vars on component root elements change
authorEvan You <yyx990803@gmail.com>
Fri, 16 Jul 2021 16:29:09 +0000 (12:29 -0400)
committerEvan You <yyx990803@gmail.com>
Fri, 16 Jul 2021 18:30:49 +0000 (14:30 -0400)
Now uses MutationObserver to ensure it works even for HOCs

fix #3894

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

index a72d0a9c2df02025af981184a16321e7d0accaff..2ece460fd7a9bcd208f5c69fb2447a105433f87b 100644 (file)
@@ -7,7 +7,8 @@ import {
   reactive,
   nextTick,
   ComponentOptions,
-  Suspense
+  Suspense,
+  FunctionalComponent
 } from '@vue/runtime-dom'
 
 describe('useCssVars', () => {
@@ -142,6 +143,40 @@ describe('useCssVars', () => {
     }
   })
 
+  // #3894
+  test('with subTree change inside HOC', async () => {
+    const state = reactive({ color: 'red' })
+    const value = ref(true)
+    const root = document.createElement('div')
+
+    const Child: FunctionalComponent = (_, { slots }) => slots.default!()
+
+    const App = {
+      setup() {
+        useCssVars(() => state)
+        return () =>
+          h(
+            Child,
+            null,
+            () => (value.value ? [h('div')] : [h('div'), h('div')])
+          )
+      }
+    }
+
+    render(h(App), root)
+    await nextTick()
+    // css vars use with fallback tree
+    for (const c of [].slice.call(root.children as any)) {
+      expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe(`red`)
+    }
+
+    value.value = false
+    await nextTick()
+    for (const c of [].slice.call(root.children as any)) {
+      expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
+    }
+  })
+
   test('with createStaticVNode', async () => {
     const state = reactive({ color: 'red' })
     const root = document.createElement('div')
index 3253dd22731a781e20df452c00082cfb0c075e62..510e81b065b5cfe1efb2ce377def72126c20059a 100644 (file)
@@ -1,12 +1,12 @@
 import {
   getCurrentInstance,
-  onMounted,
   warn,
   VNode,
   Fragment,
   Static,
-  onUpdated,
-  watchEffect
+  watchPostEffect,
+  onMounted,
+  onUnmounted
 } from '@vue/runtime-core'
 import { ShapeFlags } from '@vue/shared'
 
@@ -27,8 +27,12 @@ export function useCssVars(getter: (ctx: any) => Record<string, string>) {
 
   const setVars = () =>
     setVarsOnVNode(instance.subTree, getter(instance.proxy!))
-  onMounted(() => watchEffect(setVars, { flush: 'post' }))
-  onUpdated(setVars)
+  watchPostEffect(setVars)
+  onMounted(() => {
+    const ob = new MutationObserver(setVars)
+    ob.observe(instance.subTree.el!.parentNode, { childList: true })
+    onUnmounted(() => ob.disconnect())
+  })
 }
 
 function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {