vben
2020-11-03 bcab4b774d384a5de9b87a0c700a9937c79eb5cd
提交 | 用户 | age
2f6253 1 import { ref, Ref, isRef, watch } from '@vue/runtime-dom'
2
3 export default function useCssVar(
4   prop: string,
5   refEl?: Ref<HTMLElement | null>
6 ) {
7   const refVar = ref('')
8   let el: HTMLElement = document.documentElement
9
10   if (isRef(refEl)) {
11     watch(
12       refEl,
13       () => {
14         if (refEl.value) {
15           el = refEl.value as HTMLElement
16           refVar.value = getComputedStyle(el).getPropertyValue(prop)
17         }
18       },
19       { immediate: true }
20     )
21   } else {
22     refVar.value = getComputedStyle(el).getPropertyValue(prop)
23   }
24
25   watch(
26     refVar,
27     val => {
28       el && el.style.setProperty(prop, val)
29     },
30     { immediate: true }
31   )
32
33   return refVar
34 }