问题描述
我想做什么?
我有一个组件库网站,我想在其中显示不同的颜色主题。我有一个选择框,用户可以在其中切换不同的主题。
// 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
向根元素 div 添加一个类:
示例:如果选择了 Blueberry,则在根 div 元素上应用“blueberry-theme”类。
<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>