Skip to content

Commit

Permalink
fix(sfc): fix style variables injection on static vnode (#3847)
Browse files Browse the repository at this point in the history
fix #3841
  • Loading branch information
edison1105 committed Jul 14, 2021
1 parent 03e2684 commit 6a0c7cd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
23 changes: 23 additions & 0 deletions packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ref,
render,
useCssVars,
createStaticVNode,
h,
reactive,
nextTick,
Expand Down Expand Up @@ -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')
}
})
})
20 changes: 17 additions & 3 deletions packages/runtime-dom/src/helpers/useCssVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
warn,
VNode,
Fragment,
Static,
onUpdated,
watchEffect
} from '@vue/runtime-core'
Expand Down Expand Up @@ -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))
}
}

0 comments on commit 6a0c7cd

Please sign in to comment.