vue 换肤
先看效果 亮色
暗色
原理是基本css变量去实现 用二套css
在src下新建theme.css
:root 相当于html
html[data-theme=‘dark’] === html 有 data-theme 属性并且 属性值为 dark
原理其实 就是当切换时 给html加上自定义属性 然后样式覆盖
:root{
--text-color:#333;
--bg1:#c7ffdd;
--bg2:#fbd988;
}
html[data-theme='dark']{
--text-color:#fff;
--bg1:#102128;
--bg2:#2d5567;
}
main.ts 导入
import './theme.css'
新建个全局的变量 light dark
进行本地存储 防止 刷新丢失
监听值得变化 当变化的时候 给html元素添加自定义属性 data-theme
import { watchEffect } from 'vue'
import {ref} from 'vue'
const LOCAL_KEY = '__theme__'
const theme =ref(localStorage.getItem('LOCAL_KEY') || 'light')
watchEffect(()=>{
document.documentElement.dataset.theme = theme.value
localStorage.setItem('LOCAL_KEY',theme.value)
})
export default function useTheme(){
return {
theme
}
}
切换主题色
<template>
<el-switch v-model="value" @click="checkFn" />
</template>
<script setup lang="ts">
import { ref } from "vue";
import useTheme from "../utils/useTheme";
const { theme } = useTheme();
const value = ref(true);
const checkFn = () => {
theme.value = theme.value === "dark" ? "light" : "dark";
};
</script>