本文主要实现点击切换按钮之后进行主题切换,并将主题存储在localstore中,使得页面主题不会刷新之后就失效,默认读取的主题从localstore中读取。
一、效果图
白天:
暗夜:
二、实现
1.在src\main.ts中添加element plus的相关依赖
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/theme-chalk/display.css'
// 暗黑主题
import 'element-plus/theme-chalk/dark/css-vars.css'
//全局注册图标组件
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
2.在src\components\theme-switch\index.vue中写入以下代码
<template>
<div>
<el-switch
@change="changeDark"
v-model="dark"
class="theme-chan"
style="margin-left: 15px"
size="large"
inline-prompt
active-icon="Moon"
inactive-icon="Sunny"
/>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
const dark = ref(false);
// 在页面加载时从浏览器缓存获取主题选择
onMounted(() => {
const savedTheme = localStorage.getItem("theme");
if (savedTheme === "dark") {
dark.value = true;
applyTheme("dark");
}
});
// 主题切换函数
const changeDark = () => {
const newTheme = dark.value ? "dark" : "";
localStorage.setItem("theme", newTheme); // 将主题选择存储到浏览器缓存中
applyTheme(newTheme); // 应用主题样式
};
// 应用主题样式函数
const applyTheme = (theme: string) => {
let html = document.documentElement;
html.className = theme;
};
</script>
<style></style>
3.在view文件夹新建一个index.vue页面,或者直接在你想引入的界面里引入
<template>
<div>
<div class="switch">
<theme-switch />
<lang-switch />
</div>
<div class="test">
<el-card class="test-card">
<h1>主题切换演示</h1>
</el-card>
</div>
</div>
</template>
<script lang="ts" setup>
import themeSwitch from './components/theme-toggle/index.vue'
</script>
<style scoped>
.test {
/* text-align: center; */
width: 800px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.test-card {
width: 800px;
border-radius: 25px;
}
.switch {
width: 120px;
display: flex;
justify-content: center;
align-items: center;
margin-top: 0px;
float: right;
margin-right: 60px;
}
</style>
三、运行
运行之后即可得到和效果图一样的效果