Skip to content

Commit

Permalink
feat(runtime-dom): useCssVars
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jul 9, 2020
1 parent 18c537d commit 9f706a9
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 5 deletions.
2 changes: 0 additions & 2 deletions packages/runtime-core/src/index.ts
Expand Up @@ -65,8 +65,6 @@ export {
} from './components/BaseTransition'
// For using custom directives
export { withDirectives } from './directives'
// SFC CSS Modules
export { useCSSModule } from './helpers/useCssModule'
// SSR context
export { useSSRContext, ssrContextKey } from './helpers/useSsrContext'

Expand Down
@@ -1,8 +1,7 @@
import { getCurrentInstance } from '../component'
import { warn, getCurrentInstance } from '@vue/runtime-core'
import { EMPTY_OBJ } from '@vue/shared'
import { warn } from '../warning'

export const useCSSModule = (name = '$style'): Record<string, string> => {
export function useCSSModule(name = '$style'): Record<string, string> {
if (!__GLOBAL__) {
const instance = getCurrentInstance()!
if (!instance) {
Expand Down
41 changes: 41 additions & 0 deletions packages/runtime-dom/src/helpers/useCssVars.ts
@@ -0,0 +1,41 @@
import {
ComponentPublicInstance,
getCurrentInstance,
onMounted,
watchEffect,
warn,
VNode,
Fragment
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared/src'

export function useCSSVars(
getter: (ctx: ComponentPublicInstance) => Record<string, string>
) {
const instance = getCurrentInstance()
if (!instance) {
__DEV__ &&
warn(`useCssVars is called without current active component instance.`)
return
}
onMounted(() => {
watchEffect(() => {
setVarsOnVNode(instance.vnode, getter(instance.proxy!))
})
})
}

function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
// 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
for (const key in vars) {
style.setProperty(`--${key}`, vars[key])
}
} else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
}
}
4 changes: 4 additions & 0 deletions packages/runtime-dom/src/index.ts
Expand Up @@ -113,6 +113,10 @@ function normalizeContainer(container: Element | string): Element | null {
return container
}

// SFC CSS utilities
export { useCSSModule } from './helpers/useCssModule'
export { useCSSVars } from './helpers/useCssVars'

// DOM-only components
export { Transition, TransitionProps } from './components/Transition'
export {
Expand Down

0 comments on commit 9f706a9

Please sign in to comment.