/
index.ts
49 lines (44 loc) · 1.22 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { computed, ref, unref, watch } from 'vue-demi'
import type { MaybeRef } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
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 target
* @param initialValue
* @param options
*/
export function useCssVar(
prop: MaybeRef<string>,
target?: MaybeElementRef,
{ window = defaultWindow, initialValue = '' }: UseCssVarOptions = {},
) {
const variable = ref(initialValue)
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)
watch(
[elRef, () => unref(prop)],
([el, prop]) => {
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(prop)
variable.value = value || initialValue
}
},
{ immediate: true },
)
watch(
variable,
(val) => {
if (elRef.value?.style)
elRef.value.style.setProperty(unref(prop), val)
},
)
return variable
}