本文将介绍如何使用 Vue、TailwindCSS 和 VueUse 实现暗黑主题及其切换功能。
1. 基本实现
首先,安装 VueUse:
npm install @vueuse/core
然后,在 Vue 组件中使用 useColorMode:
<template>
<div>
<button @click="toggleColorMode">
切换到{{themeStore === 'dark' ? '明亮' : '暗黑' }}模式
</button>
</div>
</template>
<script setup>
import { useColorMode } from '@vueuse/core'
const { system: themeSystem, store: themeStore } = useColorMode();
const toggleColorMode = () => {
themeStore.value = themeStore.value === 'dark' ? 'light' : 'dark'
}
</script>
这里我们使用了 Vueuse 的 useColorMode 功能,返回两个变量:
> system: 系统偏好的颜色模式
> store: LocalStorge 中自动存储的颜色模式
因此,通过点击按钮,我们设置了 store 的值,会自动在 <html> 上增加 dark 类(这是tailwindcss设置为暗黑模式的默认类),从而在 Light 和 Dark 模式之间切换。
2. 调整背景色和元素颜色
这里,我们可以通过调整项目根目录的 index.html 实现页面背景色的切换。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GithubStar</title>
<meta
name="description"
content="GithubStar 是一个自动互相点赞, 提升 Github 项目 Star 数量的平台. 免费刷 Star (刷星刷赞), 刷 Follow (刷关注), 提高开源项目知名度."
/>
<meta name="keywords" content="Github, Star, 互赞, 刷赞, 开源项目" />
</head>
<body class="antialiased text-slate-900 dark:text-slate-200 bg-white dark:bg-slate-900">
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
这里我们调整了 <body> 元素的 dark:text-slate-200 dark:bg-slate-900 来调整了暗黑模式的默认前景背景色。
对于元素颜色,我们也可以用类似的 "dark:" 类来调整暗黑模式下的类。
3. 案例分析
上述方式已经使用在开源项目 GithubStar.Pro 中,你可以点击右上角的切换按钮,以在暗黑、明亮、跟随系统三种模式之间切换。该项目的源码在:Github。
明亮模式
暗黑模式
也欢迎大家使用开源项目互赞互粉平台 GithubStar.Pro,提高你的项目知名度,快速涨星。
感谢大家的收看,祝大家 Happy Coding.