Vue3 实现网站黑夜白天切换

112 阅读1分钟

前言

现在网站的黑夜白天切换越来越常见,我的博客网站也实现了黑夜白天的切换,实现黑夜白天切换有多种方式,下面我将介绍一下在 Vue3 中如何实现黑夜白天的

具体实现

我是使用了 css 变量和类选择器实现黑夜白天的切换,先分别编写好在全局的变量值以及在dark类下的变量值

创建 theme.css 文件

/* 全局/白天 */
:root {
	/* 主题颜色 */
	--theme-color: #ffffff;
}

/* 黑夜 */
.dark {
    /* 主题颜色 */
	--theme-color: #232424;
}

当我们想切换黑夜的时候,只需要往 html 标签上添加 dark 类,那么 dark 类对应的 css 变量值将会生效,从而实现黑夜的切换

为了简化使用,我将黑夜白天切换封装为一个自定义 Hook

useDark

import { DARK } from '@/constant';
import useStore from '@/store';
import cache from '@/utils/cache';
import { onMounted, ref } from 'vue';

export default function useDark() {
    const isDark = ref(cache.getCache<boolean>(DARK) || false);

    // 设置黑夜
	const setDark = () => {
		const htmlElement = document.documentElement;
		htmlElement.classList.add('dark');
	};
    
    // 移除
	const removeAllTheme = () => {
		const htmlElement = document.documentElement;
		htmlElement.classList.value = '';
		theme.value = '';
	};

	// 切换黑夜白天
	const changeDark = () => {
          removeAllTheme();
		if (isDark.value) {
			// 持久化,存入localStorage
			cache.setCache<boolean>(DARK, false);
			isDark.value = false;
		} else {
			setDark();
			// 持久化,存入localStorage
			cache.setCache<boolean>(DARK, true);
			isDark.value = true;
		}
	};

	// 是否为晚上,这里主要是实现到晚上的时候自动切换为黑夜
	const nowIsDark = () => {
		const date = new Date();
		const hour = date.getHours();
		if (hour >= 18 || hour <= 6) {
			changeDark();
		}
	};

	onMounted(() => {
        if (cache.getCache<boolean>(DARK) === null) {
            nowIsDark();
        } else {
            if (isDark.value) setDark();
        }
	});

	return {
		isDark,
		changeDark
	};
}

具体使用

zb-dark 黑夜白天切换组件封装

<template>
	<div class="theme-container" @click="changeDark">
		<el-icon size="20" v-if="isDark"><Sunny /></el-icon>
		<el-icon size="20" v-if="!isDark"><Moon /></el-icon>
	</div>
</template>

<script lang="ts" setup>
	import { Moon, Sunny } from '@element-plus/icons-vue';
	import useTheme from '@/hooks/useDark';

	const { isDark, changeDark } = useDark();
</script>

<style lang="scss" scoped>
	.theme-container {
		display: flex;
		align-items: center;
	}

	.theme-container:hover {
		cursor: pointer;
	}
</style>

组件使用

<template>
	<zb-dark></zb-dark>
</template>

<script lang="ts" setup>
	import zbDark from '@/components/common/zb-dark.vue';
</script>

<style lang="scss" scoped></style>

大功告成!