useCssVar.ts 683 B

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