在运行时动态更新 Tailwindcss 中的 CSS 个变量定义

Dynamically update CSS variables definitions in Tailwindcss during runtime

我想做什么?

我有一个组件库网站,我想在其中显示不同的颜色主题。我有一个 select 框,用户可以在其中切换不同的主题。

我有两个 css 文件,我们将它们命名为西瓜和蓝莓。

// blueberry/index/.css
:root {
--color-1: indigo;
}
// watermelon/index/.css
:root {
--color-1: green;
}

和我的 tailwind.config.js

//tailwind.config.js
theme: {
 extend: {
  color: {
   primary: "var(--color-1)"

代码上发生了什么

我在 selectedTheme 上有一个观察者,所以每次值更改时,我都会导入正确的主题 css 文件。

import { ref, watch } from "vue"

export default {
  setup() {
    const selectedTheme = ref("watermelon")
    const themeOptions = [
      { name: "Blueberry", value: "blueberry" },
      { name: "Watermelon", value: "watermelon" },
    ]
    async function importTheme(theme) {
      try {
        await import(`../themes/${theme}/index.css`)
      } catch (error) {
        console.log(error)
      }
    }
    watch(
      selectedTheme,
      async newValue => {
        console.log("changing", newValue)
        await importTheme(newValue)
      },
      { immediate: true }
    )
    return { themeOptions, selectedTheme }
  },
}
</script>
<style>
#app {
  font-family: "Poppins", sans-serif;
}
</style>

现在发生了什么

第一次切换时->主题从西瓜切换到蓝莓->组件颜色从绿色变为靛蓝。

在第二次切换后 -> 没有任何反应,组件颜色没有改变。

我不确定这里发生了什么。有人可以启发我或指出正确的方向吗?

应该发生什么

即使在第一次切换之后也能正常工作。从绿色切换到靛蓝,然后再切换回绿色。

我最后做的是像这样声明 css 变量:

.blueberry-theme {
 --color-1:indigo;
}

.watermelon-theme {
 --color-1: green;
}

并且在 vue 组件观察器上,每次更改 selectedTheme 时,我使用 document.documentElement.className 添加一个 class 到根元素 div:

示例:如果选择蓝莓,“蓝莓主题”class 将应用于根 div 元素。

<template>
  <Select :options="themeOptions" v-model="selectedTheme" />
</template>

<script>
import { ref, watch } from "vue"
export default {
  setup() {
    const selectedTheme = ref("blueberry-theme")

    const themeOptions = [
      { name: "Blueberry", value: "blueberry-theme" },
      { name: "Watermelon", value: "watermelon-theme" },
    ]

    function setTheme(theme) {
      document.documentElement.className = theme
    }

    watch(
      selectedTheme,
      async newValue => {
        await setTheme(newValue)
      },
      { immediate: true }
    )

    return { themeOptions, selectedTheme }
  },
}
</script>

不确定这是否是您想要的,但您可以通过以下方式动态更改 css 变量:

  if (typeof window !== 'undefined') {
      document.documentElement.style.setProperty('--color-1', someCoolColor)
  }

这将反映到使用此变量的顺风样式中。