在Vue项目中实现主题颜色切换,你可以通过动态改变html元素的data-theme属性来实现。这里是一个基本的示例,包括如何在Vue组件中切换主题,以及如何使用CSS变量来定义颜色。
//main.js文件
import "./them.css";
//./them.css
/* 定义暗色主题 */
html[data-theme='dark'] {
--text-color: #ffffff;
--bg1: #5b5c5b;
--bg2:#7c4dc3;
--bg3:#afc315;
/* 其他你需要的颜色变量 */
}
/* 定义默认(或亮色)主题 */
:root {
--text-color: #ffffff;
--bg1: #517fcf;
--bg2:rgb(188, 52, 116);
/* 其他你需要的颜色变量 */
}
/* 使用CSS变量来设置元素的样式 */
body {
color: var(--text-color);
background-color: var(--bg1);
/* 其他样式 */
}
//useTheme.ts
import { ref, watchEffect } from "vue";
const key = "__theme__";
const theme = ref(localStorage.getItem(key) || "dark");
watchEffect(() => {
document.documentElement.dataset.theme = theme.value;
localStorage.setItem(key, theme.value);
});
export function useTheme() {
return {
theme,
toggleTheme() {
theme.value = theme.value === "light" ? "dark" : "light";
},
};
}
//home.vue
<template>
<div>
<van-switch
@change="toggleTheme"
v-model="checked"
active-color="#afc315"
inactive-color="#4dc3aa"
/>
<div class="home">9900001</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import { useTheme } from "../../utils/useTheme";
const { theme, toggleTheme } = useTheme();
const checked = ref(theme.value === "dark" ? true : false);
</script>
<style scoped>
.home {
margin-top: 40px;
margin-bottom: 40px;
width: 400px;
height: 400px;
background: var(--bg2);
text-align: center;
}
</style>