Skip to content

Commit 6647e34

Browse files
committed
refactor: adjust useCSSVars scoped usage
1 parent 879ea17 commit 6647e34

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

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

+3-2
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,14 @@ describe('useCssVars', () => {
6464
}))
6565
})
6666

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

7070
await assertCssVars(
7171
state => ({
72+
__scopeId: id,
7273
setup() {
73-
useCSSVars(() => state, id)
74+
useCSSVars(() => state, true)
7475
return () => h('div')
7576
}
7677
}),

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

+16-6
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@ import {
55
watchEffect,
66
warn,
77
VNode,
8-
Fragment
8+
Fragment,
9+
ComponentInternalInstance
910
} from '@vue/runtime-core'
1011
import { ShapeFlags } from '@vue/shared/src'
1112

1213
export function useCSSVars(
1314
getter: (ctx: ComponentPublicInstance) => Record<string, string>,
14-
scopeId?: string
15+
scoped = false
1516
) {
1617
const instance = getCurrentInstance()
1718
if (!instance) {
@@ -21,27 +22,36 @@ export function useCSSVars(
2122
}
2223
onMounted(() => {
2324
watchEffect(() => {
24-
setVarsOnVNode(instance.vnode, getter(instance.proxy!), scopeId)
25+
setVarsOnVNode(
26+
instance.subTree,
27+
getter(instance.proxy!),
28+
instance,
29+
scoped
30+
)
2531
})
2632
})
2733
}
2834

2935
function setVarsOnVNode(
3036
vnode: VNode,
3137
vars: Record<string, string>,
32-
scopeId?: string
38+
owner: ComponentInternalInstance,
39+
scoped: boolean
3340
) {
3441
// drill down HOCs until it's a non-component vnode
3542
while (vnode.component) {
3643
vnode = vnode.component.subTree
3744
}
3845
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
3946
const style = vnode.el.style
40-
const prefix = scopeId ? scopeId + '-' : ''
47+
const prefix =
48+
scoped && owner.type.__scopeId ? `${owner.type.__scopeId}-` : ``
4149
for (const key in vars) {
4250
style.setProperty(`--${prefix}${key}`, vars[key])
4351
}
4452
} else if (vnode.type === Fragment) {
45-
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, scopeId))
53+
;(vnode.children as VNode[]).forEach(c =>
54+
setVarsOnVNode(c, vars, owner, scoped)
55+
)
4656
}
4757
}

0 commit comments

Comments
 (0)