借助 CSS 变量定义颜色值,在 Tailwind 配置里引用这些变量,通过修改根元素上的 CSS 变量值来实现主题切换。
:root 中定义,其他主题通过自定义属性(如 [data - theme="dark"])定义,示例如下:/* 默认主题 */
:root {
--primary-color: #007bff;
--secondary-color: #6c757d;
}
/* 黑暗主题 */
[data-theme="dark"] {
--primary-color: #212529;
--secondary-color: #adb5bd;
}
tailwind.config.js 文件,在 theme.extend.colors 中使用 CSS 变量定义颜色,示例如下:module.exports = {
darkMode: "class", //默认情况下,Tailwind 未开启深色模式变体,需要手动开启。
theme: {
extend: {
colors: {
primary: "var(--primary-color)",
secondary: "var(--secondary-color)"
}
}
}
};
<template>
<el-button type="primary" @click="toggleDark()">换色</el-button>
<!-- tailwind -->
<div class="bg-primary">tailwind1</div>
<div class="bg-secondary">tailwind2</div>
</template>
<script lang="ts" setup>
import { useDark, useToggle } from "@vueuse/core";
const isDark = useDark();
const toggleDark = useToggle(isDark);
</script>
这种方法灵活性高,能够在运行时动态切换主题,且代码结构清晰,便于维护和扩展新的主题。