kotcich
@kotcich
Я скучный.

Можно ли отслеживать css переменные с помощью computed?

Или по другому как то, в общем как?
  • Вопрос задан
  • 105 просмотров
Решения вопроса 1
Aetae
@Aetae Куратор тега Vue.js
Тлен
Вот по-быстрому накидал в качестви зарядки такой кастомный дерьмохук (который ни в коем случае нельзя использовать в проде, только в целях демонстрации. :) ):
import { Ref, computed, ref, watch, onMounted, onUnmounted } from 'vue';

function isHTMLElement(arg: unknown): arg is HTMLElement {
  return !!arg && arg instanceof HTMLElement;
}

function useCSSVariable(
  variable: string,
  el: HTMLElement | Ref<HTMLElement> = document.documentElement
) {
  if (!variable.startsWith('--')) variable = `--${variable}`;
  if (!isHTMLElement(el)) watch(el, value => (el = value), { immediate: true });

  const prev = ref();

  let timeoutId: number;
  const interval = () => {
    const current = isHTMLElement(el)
      ? getComputedStyle(el).getPropertyValue(variable)
      : null;

    if (current !== prev.value) prev.value = current;

    timeoutId = window.setTimeout(interval, 100);
  };

  onMounted(() => {
    interval();
  });

  onUnmounted(() => {
    clearTimeout(timeoutId);
  });

  return computed<string>({
    set(value) {
      let current: null | string = null;

      if (isHTMLElement(el)) {
        el.style.setProperty(variable, value);
        current = el.style.getPropertyValue(variable);
      }

      if (prev.value !== current) prev.value = current;
    },
    get() {
      return prev.value;
    }
  });
}


Ещё раз - использовать это не надо, это скорее шутка. Что надо - выяснить твою задачу и решать её нормально по-человечески.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы