@lingxin-link/theme-toggle

通用 Vue3 主题切换器:useThemeToggle hook + ThemeTabs 滑块切换组件,内置 view-transition 主题切换动画样式
21,143
Install
npm install @lingxin-link/theme-toggle
Latest Version:1.0.2
Vue:3
Last Updated:Oct 3, 2026
Links: npm
Maintainer: lingxin_tech

@lingxin-link/theme-toggle

通用 Vue3 主题切换器(浅色 / 深色),TypeScript 编写,tsdown 打包。

  • useThemeToggle:hooks 式用法(类似 vueuse 的 useDark),提供响应式 theme 与 setTheme / toggleTheme / getCurrentTheme 三个函数
  • ThemeTabs:日/夜双 tab 滑块切换组件,UI 自带样式注入,宿主零配置
  • animation.css:主题切换的 view-transition 动画(8° 斜切擦除),引入即生效

主题机制

主题写入 <html theme-mode="light|dark">,配合使用 CSS Vars 双主题 token 的组件库(如 --td-bg-color-*、--td-text-color-*)时深浅色自动生效,页面无需为深色单独写样式。

初始值优先级:localStorage 缓存 → 系统偏好(prefers-color-scheme)。跨标签页通过 storage 事件自动同步。

安装

pnpm add @lingxin-link/theme-toggle

要求 Vue >= 3.3(peer dependency)。

使用

Hook

import { useThemeToggle } from "@lingxin-link/theme-toggle";

const { theme, setTheme, toggleTheme, getCurrentTheme } = useThemeToggle();

theme.value; // "light" | "dark"(响应式,只读)
setTheme("dark"); // 切换主题,默认带动画
setTheme("dark", { animation: false }); // 直接切换,不播动画
toggleTheme(); // 在 light/dark 间切换
getCurrentTheme(); // 读取 <html theme-mode>,无值时回落内存状态

滑块组件

import { ThemeTabs } from "@lingxin-link/theme-toggle";
<ThemeTabs />

组件内部调用 useThemeToggle(),点击日/夜图标即切换主题并播动画;首次挂载自动向 document.head 注入组件样式(幂等)。

切换动画

import "@lingxin-link/theme-toggle/animation.css";

引入后,setTheme / toggleTheme 内部自动以 document.startViewTransition 包裹主题切换(浏览器不支持时静默降级为直接切换)。动画基于 view-transition API,无需其他配置。

API

useThemeToggle(options?)

参数 类型 默认 说明
options.storageKey string "lingxin-theme" localStorage 持久化 key;传 "" 关闭持久化。仅首次调用生效(全局单例状态)
options.animation(setTheme/toggleTheme 第二参 .animation) boolean true 是否用 view-transition 播放切换动画
返回 类型 说明
theme Readonly<Ref<"light" | "dark">> 当前主题(响应式)
setTheme (next: Theme, options?: { animation?: boolean }) => void 设置主题
toggleTheme (options?: { animation?: boolean }) => void 切换主题
getCurrentTheme () => Theme 读 <html theme-mode>,无值回落内存状态

ThemeTabs

无 props。样式颜色取宿主主题 token(--td-*),深浅色自动适配;日/夜图标的激活色为固定值,不随主题变化。

开发

pnpm install   # 或 npm install
pnpm build     # tsdown 打包,输出 dist/(js + dts + animation.css)
pnpm dev       # watch 模式

目录结构

src/
├── index.ts            # 入口,统一导出
├── useThemeToggle.ts   # 主题 hook(单例状态 + 持久化 + 跨标签页同步)
├── theme-tabs.ts       # ThemeTabs 滑块组件(渲染函数,无模板编译依赖)
├── theme-tabs-style.ts # 组件样式与运行时注入
└── animation.css       # view-transition 切换动画

Version History

Version Released License
1.0.2
1.0.1
1.0.0