/
index.ts
47 lines (43 loc) · 1.2 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
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'
/**
* Manipulate CSS variables.
*
* @see https://vueuse.org/useCssVar
* @param prop
* @param target
* @param initialValue
* @param options
*/
export function useCssVar(
prop: MaybeRef<string>,
target?: MaybeElementRef,
initialValue?: MaybeRef<string>,
{ window = defaultWindow }: ConfigurableWindow = {},
) {
const variable = ref('')
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)
const _initialValue = unref(initialValue)
watch(
[elRef, () => unref(prop)],
([el, prop]) => {
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(prop)
variable.value = value == '' ? _initialValue : value
}
},
{ immediate: true },
)
watch(
variable,
(val) => {
if (elRef.value?.style)
elRef.value.style.setProperty(unref(prop), val)
},
)
return variable
}