Skip to content

Commit

Permalink
feat(useCssVar): support initialValue (#1619)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
jd-solanki and antfu committed May 31, 2022
1 parent d64070e commit bbb8334
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
3 changes: 3 additions & 0 deletions packages/core/useCssVar/index.md
Expand Up @@ -17,4 +17,7 @@ const color = useCssVar('--color', el)
const elv = ref(null)
const key = ref('--color')
const colorVal = useCssVar(key, elv)

const someEl = ref(null)
const color = useCssVar('--color', someEl, { initialValue: '#eee' })
```
17 changes: 12 additions & 5 deletions packages/core/useCssVar/index.ts
Expand Up @@ -5,27 +5,34 @@ import { defaultWindow } from '../_configurable'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'

export interface UseCssVarOptions extends ConfigurableWindow {
initialValue?: string
}

/**
* Manipulate CSS variables.
*
* @see https://vueuse.org/useCssVar
* @param prop
* @param el
* @param target
* @param initialValue
* @param options
*/
export function useCssVar(
prop: MaybeRef<string>,
target?: MaybeElementRef,
{ window = defaultWindow }: ConfigurableWindow = {},
{ window = defaultWindow, initialValue = '' }: UseCssVarOptions = {},
) {
const variable = ref('')
const variable = ref(initialValue)
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)

watch(
[elRef, () => unref(prop)],
([el, prop]) => {
if (el && window)
variable.value = window.getComputedStyle(el).getPropertyValue(prop)
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(prop)
variable.value = value || initialValue
}
},
{ immediate: true },
)
Expand Down

0 comments on commit bbb8334

Please sign in to comment.