]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(sfc): fix style variables injection on static vnode (#3847)
authoredison <daiwei521@126.com>
Wed, 14 Jul 2021 22:08:12 +0000 (06:08 +0800)
committerGitHub <noreply@github.com>
Wed, 14 Jul 2021 22:08:12 +0000 (18:08 -0400)
fix #3841

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

index ae86e57ba5d86d635ba1d3de5fc6ed32c864f51b..a72d0a9c2df02025af981184a16321e7d0accaff 100644 (file)
@@ -2,6 +2,7 @@ import {
   ref,
   render,
   useCssVars,
+  createStaticVNode,
   h,
   reactive,
   nextTick,
@@ -140,4 +141,26 @@ describe('useCssVars', () => {
       expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
     }
   })
+
+  test('with createStaticVNode', async () => {
+    const state = reactive({ color: 'red' })
+    const root = document.createElement('div')
+
+    const App = {
+      setup() {
+        useCssVars(() => state)
+        return () => [
+          h('div'),
+          createStaticVNode('<div>1</div><div><span>2</span></div>', 2),
+          h('div')
+        ]
+      }
+    }
+
+    render(h(App), root)
+    await nextTick()
+    for (const c of [].slice.call(root.children as any)) {
+      expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
+    }
+  })
 })
index 82c48e33a04251c6a04abe499d9a181afc03fb85..3253dd22731a781e20df452c00082cfb0c075e62 100644 (file)
@@ -4,6 +4,7 @@ import {
   warn,
   VNode,
   Fragment,
+  Static,
   onUpdated,
   watchEffect
 } from '@vue/runtime-core'
@@ -47,11 +48,24 @@ function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
   }
 
   if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
-    const style = vnode.el.style
+    setVarsOnNode(vnode.el as Node, vars)
+  } else if (vnode.type === Fragment) {
+    ;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
+  } else if (vnode.type === Static) {
+    let { el, anchor } = vnode
+    while (el) {
+      setVarsOnNode(el as Node, vars)
+      if (el === anchor) break
+      el = el.nextSibling
+    }
+  }
+}
+
+function setVarsOnNode(el: Node, vars: Record<string, string>) {
+  if (el.nodeType === 1) {
+    const style = (el as HTMLElement).style
     for (const key in vars) {
       style.setProperty(`--${key}`, vars[key])
     }
-  } else if (vnode.type === Fragment) {
-    ;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
   }
 }