refactor: shorten scoped css var / animation prefix

This commit is contained in:
Evan You
2020-07-10 18:47:31 -04:00
parent 73807aeaf7
commit 5f271515cf
4 changed files with 35 additions and 29 deletions

View File

@@ -15,17 +15,21 @@ describe('useCssVars', () => {
const state = reactive({ color: 'red' })
const App = getApp(state)
const root = document.createElement('div')
const prefix = scopeId ? `${scopeId}-` : ``
const prefix = scopeId ? `${scopeId.replace(/^data-v-/, '')}-` : ``
render(h(App), root)
for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${prefix}color`))
expect(
(c as HTMLElement).style.getPropertyValue(`--${prefix}color`)
).toBe(`red`)
}
state.color = 'green'
await nextTick()
for (const c of [].slice.call(root.children as any)) {
expect((c as HTMLElement).style.getPropertyValue(`--${prefix}color`))
expect(
(c as HTMLElement).style.getPropertyValue(`--${prefix}color`)
).toBe('green')
}
}
@@ -65,7 +69,7 @@ describe('useCssVars', () => {
})
test('with <style scoped>', async () => {
const id = 'v-12345'
const id = 'data-v-12345'
await assertCssVars(
state => ({

View File

@@ -5,8 +5,7 @@ import {
watchEffect,
warn,
VNode,
Fragment,
ComponentInternalInstance
Fragment
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared/src'
@@ -20,14 +19,15 @@ export function useCSSVars(
warn(`useCssVars is called without current active component instance.`)
return
}
const prefix =
scoped && instance.type.__scopeId
? `${instance.type.__scopeId.replace(/^data-v-/, '')}-`
: ``
onMounted(() => {
watchEffect(() => {
setVarsOnVNode(
instance.subTree,
getter(instance.proxy!),
instance,
scoped
)
setVarsOnVNode(instance.subTree, getter(instance.proxy!), prefix)
})
})
}
@@ -35,8 +35,7 @@ export function useCSSVars(
function setVarsOnVNode(
vnode: VNode,
vars: Record<string, string>,
owner: ComponentInternalInstance,
scoped: boolean
prefix: string
) {
// drill down HOCs until it's a non-component vnode
while (vnode.component) {
@@ -44,14 +43,10 @@ function setVarsOnVNode(
}
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
const style = vnode.el.style
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, owner, scoped)
)
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, prefix))
}
}