项目主题切换小案例:
<template>
<button @click="toggleTheme">切换主题</button>
<div class="theme-box">这事一个切换验证</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
// 写法一
// const toggleTheme = () => {
// const htmlEl = document.documentElement;
// const currentTheme = htmlEl.getAttribute("data-theme");
// const newTheme = currentTheme === "dark" ? "light" : "dark";
// htmlEl.setAttribute("data-theme", newTheme);
// };
// onMounted(() => { toggleTheme() });
// 写法二
// 响应式主题状态
const theme = ref('light')
// 切换主题函数
function toggleTheme() {
theme.value = theme.value === 'light' ? 'dark' : 'light'
}
// 在组件挂载时设置 data-theme 属性到 html 标签
onMounted(() => {
document.documentElement.setAttribute('data-theme', theme.value)
})
// 监听 theme 变化,同步更新 html 的 data-theme 属性
watch(theme, (newVal) => {
document.documentElement.setAttribute('data-theme', newVal)
})
</script>
<style>
/* 定义全局变量 */
:root[data-theme="light"] {
--bg-color: rgb(206, 219, 156);
--text-color: black;
}
:root[data-theme="dark"] {
--bg-color: rgb(169, 123, 221);
--text-color: white;
}
</style>
<style scoped>
.theme-box {
width: 300px;
height: 120px;
background-color: var(--bg-color);
color: var(--text-color); /* 使用定义的文本颜色变量 */
}
</style>