From bbb8334411738f128f44f35a439a9e3f4f0c5e39 Mon Sep 17 00:00:00 2001 From: JD Solanki <47495003+jd-solanki@users.noreply.github.com> Date: Tue, 31 May 2022 18:09:51 +0530 Subject: [PATCH] feat(useCssVar): support `initialValue` (#1619) Co-authored-by: Anthony Fu --- packages/core/useCssVar/index.md | 3 +++ packages/core/useCssVar/index.ts | 17 ++++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/core/useCssVar/index.md b/packages/core/useCssVar/index.md index eff4bbe4e04..f2e2bd949ba 100644 --- a/packages/core/useCssVar/index.md +++ b/packages/core/useCssVar/index.md @@ -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' }) ``` diff --git a/packages/core/useCssVar/index.ts b/packages/core/useCssVar/index.ts index e51a52a34ee..943408e35b5 100644 --- a/packages/core/useCssVar/index.ts +++ b/packages/core/useCssVar/index.ts @@ -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, 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 }, )