Vue + TailwindCSS + VueUse 实现暗黑主题切换

本文将介绍如何使用 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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值