UNPKG

@muban/muban

Version:

Writing components for server-rendered HTML

28 lines (27 loc) 1.13 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ import { unref, watchEffect } from '@vue/runtime-core'; const previousCssBindingKey = '__muban__cssValue'; export function cssBinding(target, value) { return watchEffect(() => { const classes = unref(value); if (typeof classes === 'string') { // first remove the previously set classes, since our binding has changed const previousCssValue = target[previousCssBindingKey]; if (previousCssValue) { target.classList.remove(...previousCssValue.split(/\s/gi)); } // then store and set our new classes, if they exist. target[previousCssBindingKey] = classes; if (classes.length > 0) { target.classList.add(...classes.split(/\s/gi)); } } else { Object.entries(classes).forEach(([name, shouldHaveClass]) => { name.split(/\s/gi).forEach((className) => { target.classList.toggle(className, unref(shouldHaveClass)); }); }); } }); }