Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useCssVar): support initialValue #1619

Merged
merged 4 commits into from May 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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