feat(compiler-sfc): new SFC css varaible injection implementation

ref: https://github.com/vuejs/rfcs/pull/231
This commit is contained in:
Evan You
2020-11-16 18:27:15 -05:00
parent 62372e9943
commit 41bb7fa330
16 changed files with 497 additions and 341 deletions

View File

@@ -5,15 +5,18 @@ import {
warn,
VNode,
Fragment,
unref,
onUpdated,
watchEffect
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared'
/**
* Runtime helper for SFC's CSS variable injection feature.
* @private
*/
export function useCssVars(
getter: (ctx: ComponentPublicInstance) => Record<string, string>,
scoped = false
scopeId: string
) {
const instance = getCurrentInstance()
/* istanbul ignore next */
@@ -23,13 +26,8 @@ export function useCssVars(
return
}
const prefix =
scoped && instance.type.__scopeId
? `${instance.type.__scopeId.replace(/^data-v-/, '')}-`
: ``
const setVars = () =>
setVarsOnVNode(instance.subTree, getter(instance.proxy!), prefix)
setVarsOnVNode(instance.subTree, getter(instance.proxy!), scopeId)
onMounted(() => watchEffect(setVars, { flush: 'post' }))
onUpdated(setVars)
}
@@ -37,14 +35,14 @@ export function useCssVars(
function setVarsOnVNode(
vnode: VNode,
vars: Record<string, string>,
prefix: string
scopeId: string
) {
if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {
const suspense = vnode.suspense!
vnode = suspense.activeBranch!
if (suspense.pendingBranch && !suspense.isHydrating) {
suspense.effects.push(() => {
setVarsOnVNode(suspense.activeBranch!, vars, prefix)
setVarsOnVNode(suspense.activeBranch!, vars, scopeId)
})
}
}
@@ -57,9 +55,9 @@ function setVarsOnVNode(
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
const style = vnode.el.style
for (const key in vars) {
style.setProperty(`--${prefix}${key}`, unref(vars[key]))
style.setProperty(`--${scopeId}-${key}`, vars[key])
}
} else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, prefix))
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars, scopeId))
}
}