換膚能夠?qū)崿F(xiàn)的終極密碼是——CSS變量,可以為每個(gè)主題設(shè)定一組CSS變量,包含這個(gè)主題的所有顏色、字體等信息,當(dāng)需要切換主題時(shí),只需要更改使用的CSS變量組即可。
:root { --main-color: #06c;}
var()
函數(shù)來使用 CSS 變量:.header { background-color: var(--main-color);}
下面我們用Vue3+Element-plus為例,來實(shí)現(xiàn)一波高亮模式+暗黑模式兩個(gè)主題色,可參考element-plus暗黑模式介紹。
在src/styles下面新建theme.scss,把默認(rèn)暗黑主題色引入進(jìn)來,并可以在其里面覆蓋原有變量或新增一些變量
// theme.scss/** element內(nèi)置暗黑主題 */@use 'element-plus/theme-chalk/src/dark/css-vars.scss' as *;// 可以進(jìn)行一些樣式的覆蓋html { --v-bg-color: #cfcccc; // 新增}html.dark { --v-bg-color: #141414; // 新增 --el-color-primary: #409eff; // 覆蓋}
在main.ts中引入默認(rèn)主題色和暗黑模式主題色
// main.ts 文件import { createApp } from 'vue';import ElementPlus from 'element-plus';// element默認(rèn)主題import 'element-plus/dist/index.css'import './style.css';// 公共樣式,包含自定義暗黑模式,element重置樣式import './styles/index.scss';import App from './App.vue';const app = createApp(App);app.use(ElementPlus);app.mount('#app')
此時(shí)在瀏覽器控制臺(tái)就可以看到很多變量
主題切換能力其核心關(guān)注點(diǎn)為:
- 利用provide注入當(dāng)前主題及修改主題的方法,然后在組件中通過inject獲取主題及主題修改方法;
- 利用localStorage持久化存儲(chǔ)主題;
- 改變html的class屬性,進(jìn)而決定使用哪一套主題;
<script setup lang="ts">import {provide, ref, onMounted} from 'vue';import SwitchDark from './components/SwitchDark.vue';// 改變屬性,確定使用哪一套樣式const addThemeAttribute = (theme: string) => { const html = document.documentElement; html.setAttribute('class', theme);}const theme = ref(localStorage.getItem('myTheme') || 'light');onMounted(() => { addThemeAttribute(theme.value);});const setTheme = (newTheme: string) => { // 改變主題 theme.value = newTheme; addThemeAttribute(newTheme); localStorage.setItem('myTheme', newTheme);};provide('theme', { theme, setTheme});</script><template> <SwitchDark /> <div class="bg"> 我是內(nèi)容 </div></template><style scoped>.bg { background-color: var(--v-bg-color); width: 200px; height: 200px;}</style>
切換主題色肯定需要一個(gè)按鈕,下面利用el-switch實(shí)現(xiàn)了一個(gè)簡單的切換按鈕,并利用setTheme來切換對(duì)應(yīng)的主題。
<template> <el-switch v-model="isDark" inline-prompt @change="changeTheme" :active-icnotallow="Sunny" :inactive-icnotallow="Moon" size="large" /></template><script setup lang="ts">import {inject, Ref, computed} from 'vue';import {Sunny, Moon} from '@element-plus/icons-vue';const {theme, setTheme} = inject<{theme: Ref<string>, setTheme: (newTheme: string) => void}>('theme') || {};const isDark = computed(() => theme?.value === 'dark');const changeTheme = () => { console.log(theme?.value) if (theme?.value === 'light') { setTheme?.('dark'); } else { setTheme?.('light'); }};</script><style scoped></style>
本文鏈接:http://www.tebozhan.com/showinfo-26-100991-0.htmlVue3項(xiàng)目中實(shí)現(xiàn)主題切換真的很簡單?。?!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com
上一篇: 線程池是什么?線程池與連接池有什么區(qū)別?線程池工作原理是什么?
下一篇: 超級(jí)加倍:互聯(lián)網(wǎng)大廠的容災(zāi)架構(gòu)設(shè)計(jì)與落地方案(跨機(jī)房部署、同城雙活、異地多活)