Skip to content

Commit

Permalink
refactor: adjust useCSSVars scoped usage
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jul 10, 2020
1 parent 879ea17 commit 6647e34
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
5 changes: 3 additions & 2 deletions packages/runtime-dom/__tests__/helpers/useCssVars.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,14 @@ describe('useCssVars', () => {
}))
})

test('with scopeId', async () => {
test('with <style scoped>', async () => {
const id = 'v-12345'

await assertCssVars(
state => ({
__scopeId: id,
setup() {
useCSSVars(() => state, id)
useCSSVars(() => state, true)
return () => h('div')
}
}),
Expand Down
22 changes: 16 additions & 6 deletions packages/runtime-dom/src/helpers/useCssVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import {
watchEffect,
warn,
VNode,
Fragment
Fragment,
ComponentInternalInstance
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared/src'

export function useCSSVars(
getter: (ctx: ComponentPublicInstance) => Record<string, string>,
scopeId?: string
scoped = false
) {
const instance = getCurrentInstance()
if (!instance) {
Expand All @@ -21,27 +22,36 @@ export function useCSSVars(
}
onMounted(() => {
watchEffect(() => {
setVarsOnVNode(instance.vnode, getter(instance.proxy!), scopeId)
setVarsOnVNode(
instance.subTree,
getter(instance.proxy!),
instance,
scoped
)
})
})
}

function setVarsOnVNode(
vnode: VNode,
vars: Record<string, string>,
scopeId?: string
owner: ComponentInternalInstance,
scoped: boolean
) {
// drill down HOCs until it's a non-component vnode
while (vnode.component) {
vnode = vnode.component.subTree
}
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
const style = vnode.el.style
const prefix = scopeId ? scopeId + '-' : ''
const prefix =
scoped && owner.type.__scopeId ? `${owner.type.__scopeId}-` : ``
for (const key in vars) {
style.setProperty(`--${prefix}${key}`, vars[key])
}
} else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, scopeId))
;(vnode.children as VNode[]).forEach(c =>
setVarsOnVNode(c, vars, owner, scoped)
)
}
}

0 comments on commit 6647e34

Please sign in to comment.