vue配置白天-暗夜主题切换 element plus+vue3+ts

本文主要实现点击切换按钮之后进行主题切换,并将主题存储在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>

三、运行

运行之后即可得到和效果图一样的效果

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值