-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
68 lines (61 loc) · 1.64 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { useMutationObserver } from '@vueuse/core'
import { computed, ref, watch } from 'vue-demi'
import type { MaybeRefOrGetter } from '@vueuse/shared'
import { toValue } 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
/**
* Use MutationObserver to monitor variable changes
* @default false
*/
observe?: boolean
}
/**
* Manipulate CSS variables.
*
* @see https://vueuse.org/useCssVar
* @param prop
* @param target
* @param options
*/
export function useCssVar(
prop: MaybeRefOrGetter<string>,
target?: MaybeElementRef,
options: UseCssVarOptions = {},
) {
const { window = defaultWindow, initialValue = '', observe = false } = options
const variable = ref(initialValue)
const elRef = computed(() => unrefElement(target) || window?.document?.documentElement)
function updateCssVar() {
const key = toValue(prop)
const el = toValue(elRef)
if (el && window) {
const value = window.getComputedStyle(el).getPropertyValue(key)?.trim()
variable.value = value || initialValue
}
}
if (observe) {
useMutationObserver(elRef, updateCssVar, {
attributes:
true,
window,
})
}
watch(
[elRef, () => toValue(prop)],
updateCssVar,
{ immediate: true },
)
watch(
variable,
(val) => {
if (elRef.value?.style)
elRef.value.style.setProperty(toValue(prop), val)
},
)
return variable
}