Skip to content

Commit b8d329d

Browse files
committed
fix(runtime-dom): useCssVars work with createStaticVNode
chore: improve code chore: improve code
1 parent d6607c9 commit b8d329d

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

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

+23
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
ref,
33
render,
44
useCssVars,
5+
createStaticVNode,
56
h,
67
reactive,
78
nextTick,
@@ -140,4 +141,26 @@ describe('useCssVars', () => {
140141
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
141142
}
142143
})
144+
145+
test('with createStaticVNode', async () => {
146+
const state = reactive({ color: 'red' })
147+
const root = document.createElement('div')
148+
149+
const App = {
150+
setup() {
151+
useCssVars(() => state)
152+
return () => [
153+
h('div'),
154+
createStaticVNode('<div>1</div><div><span>2</span></div>', 2),
155+
h('div')
156+
]
157+
}
158+
}
159+
160+
render(h(App), root)
161+
await nextTick()
162+
for (const c of [].slice.call(root.children as any)) {
163+
expect((c as HTMLElement).style.getPropertyValue(`--color`)).toBe('red')
164+
}
165+
})
143166
})

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

+21
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
warn,
55
VNode,
66
Fragment,
7+
Static,
78
onUpdated,
89
watchEffect
910
} from '@vue/runtime-core'
@@ -53,5 +54,25 @@ function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
5354
}
5455
} else if (vnode.type === Fragment) {
5556
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
57+
} else if (vnode.type === Static) {
58+
const { el, anchor } = vnode
59+
let current: HTMLElement | null = el as HTMLElement
60+
while (current) {
61+
setVarsOnElement(current, vars)
62+
if (current === anchor) break
63+
current = current.nextSibling as HTMLElement
64+
}
65+
}
66+
67+
function setVarsOnElement(el: HTMLElement, vars: Record<string, string>) {
68+
const style = el.style
69+
for (const key in vars) {
70+
style.setProperty(`--${key}`, vars[key])
71+
}
72+
73+
for (var i = 0; i < el.children.length; i++) {
74+
const n = el.children[i]
75+
setVarsOnElement(n as HTMLElement, vars)
76+
}
5677
}
5778
}

0 commit comments

Comments
 (0)