refactor: adjust useCSSVars scoped usage

This commit is contained in:
Evan You 2020-07-10 10:19:16 -04:00
parent 879ea17985
commit 6647e34ce7
2 changed files with 19 additions and 8 deletions

View File

@ -64,13 +64,14 @@ describe('useCssVars', () => {
})) }))
}) })
test('with scopeId', async () => { test('with <style scoped>', async () => {
const id = 'v-12345' const id = 'v-12345'
await assertCssVars( await assertCssVars(
state => ({ state => ({
__scopeId: id,
setup() { setup() {
useCSSVars(() => state, id) useCSSVars(() => state, true)
return () => h('div') return () => h('div')
} }
}), }),

View File

@ -5,13 +5,14 @@ import {
watchEffect, watchEffect,
warn, warn,
VNode, VNode,
Fragment Fragment,
ComponentInternalInstance
} from '@vue/runtime-core' } from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared/src' import { ShapeFlags } from '@vue/shared/src'
export function useCSSVars( export function useCSSVars(
getter: (ctx: ComponentPublicInstance) => Record<string, string>, getter: (ctx: ComponentPublicInstance) => Record<string, string>,
scopeId?: string scoped = false
) { ) {
const instance = getCurrentInstance() const instance = getCurrentInstance()
if (!instance) { if (!instance) {
@ -21,7 +22,12 @@ export function useCSSVars(
} }
onMounted(() => { onMounted(() => {
watchEffect(() => { watchEffect(() => {
setVarsOnVNode(instance.vnode, getter(instance.proxy!), scopeId) setVarsOnVNode(
instance.subTree,
getter(instance.proxy!),
instance,
scoped
)
}) })
}) })
} }
@ -29,7 +35,8 @@ export function useCSSVars(
function setVarsOnVNode( function setVarsOnVNode(
vnode: VNode, vnode: VNode,
vars: Record<string, string>, vars: Record<string, string>,
scopeId?: string owner: ComponentInternalInstance,
scoped: boolean
) { ) {
// drill down HOCs until it's a non-component vnode // drill down HOCs until it's a non-component vnode
while (vnode.component) { while (vnode.component) {
@ -37,11 +44,14 @@ function setVarsOnVNode(
} }
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) { if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
const style = vnode.el.style const style = vnode.el.style
const prefix = scopeId ? scopeId + '-' : '' const prefix =
scoped && owner.type.__scopeId ? `${owner.type.__scopeId}-` : ``
for (const key in vars) { for (const key in vars) {
style.setProperty(`--${prefix}${key}`, vars[key]) style.setProperty(`--${prefix}${key}`, vars[key])
} }
} else if (vnode.type === Fragment) { } 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)
)
} }
} }