Vue3+Setup+TypeScript实现主题切换(浅色、深色、跟随系统)

使用 Vue 3 的 Composition API、 TypeScript 以及 <script setup> 语法糖,实现动态主题切换,能够在 ‘light’(明亮)、‘dark’(暗黑)和 ‘system’(系统)主题之间切换,并且使用 localStorage 做了状态缓存。代码十分精简,提供 JavaScript 和 TypeScript 版本,也可以在线体验此功能:play.vuejs.org

基本实现

script

  • const theme = ref<ThemeType>((localStorage.getItem('theme') as ThemeType) || 'light') 使用 Vue 的 ref 函数创建一个响应式引用,保存当前选择的主题。尝试从 localStorage 获取保存的主题,如果没有则默认为 'light'
  • watch 来观察 theme 的变化,当 theme 变化时修改 html 的 class,当 theme 设置为 ‘system’ 时,会根据当前系统的主题来设置对应的 class。
  • setTheme 函数用来将用户选择的主题保存到 localStorage 并更新 theme
  • handleChange 函数为 <select> 元素的 change 事件提供处理逻辑,它会调用 setTheme 以更新并保存用户选择的新主题。

template

显示当前主题,并有一个下拉菜单让用户选择主题。

style

定义了两个 css 变量,用于设置背景颜色和文字颜色。.dark 类通过覆盖 CSS 变量,实现暗黑模式的配色方案。

完整代码

TypeScript

<script setup lang="ts">
import { ref, watch } from 'vue'

type ThemeType = 'light' | 'dark' | 'system'

const theme = ref<ThemeType>((localStorage.getItem('theme') as ThemeType) || 'light')

watch(
  theme,
  (val) => {
    const root = window.document.documentElement

    root.classList.remove('light', 'dark')

    if (theme.value === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light'

      root.classList.add(systemTheme)
      return
    }

    root.classList.add(val)
  },
  {
    immediate: true,
  }
)

const setTheme = (value: ThemeType) => {
  localStorage.setItem('theme', value)
  theme.value = value
}

const handleChange = (
  event: Event & {
    target: HTMLSelectElement
  }
) => {
  const value = event.target.value as ThemeType
  setTheme(value)
}
</script>

<template>
  <div>
    {{ theme }}
    <select v-model="theme" @change="handleChange">
      <option value="light">Light</option>
      <option value="dark">Dark</option>
      <option value="system">System</option>
    </select>
  </div>
</template>

<style>
:root {
  --background: #ffffff;
  --text: #09090b;
}

.dark {
  --background: #09090b;
  --text: #f9f9f9;
}

html,
body,
#app {
  height: 100%;
}

body {
  background-color: var(--background);
  color: var(--text);
}
</style>

JavaScript

<script setup>
import { ref, watch } from 'vue'

const theme = ref((localStorage.getItem('theme')) || 'light')

watch(
  theme,
  (val) => {
    const root = window.document.documentElement

    root.classList.remove('light', 'dark')

    if (theme.value === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light'

      root.classList.add(systemTheme)
      return
    }

    root.classList.add(val)
  },
  {
    immediate: true,
  }
)

const setTheme = (value) => {
  localStorage.setItem('theme', value)
  theme.value = value
}

const handleChange = (event) => {
  const value = event.target.value
  setTheme(value)
}
</script>

<template>
  <div>
    {{ theme }}
    <select v-model="theme" @change="handleChange">
      <option value="light">Light</option>
      <option value="dark">Dark</option>
      <option value="system">System</option>
    </select>
  </div>
</template>

<style>
:root {
  --background: #ffffff;
  --text: #09090b;
}

.dark {
  --background: #09090b;
  --text: #f9f9f9;
}

html,
body,
#app {
  height: 100%;
}

body {
  background-color: var(--background);
  color: var(--text);
}
</style>
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下步骤在 Vue3 + Vite3 + Typescript 中使用 WangEditor 编辑器: 1. 安装 WangEditor。可以使用 npm 或 yarn 安装。 ```bash npm install wangeditor --save # 或者 yarn add wangeditor ``` 2. 在 `main.ts` 中引入 WangEditor 和 CSS 文件。 ```typescript import WangEditor from 'wangeditor'; import 'wangeditor/release/wangEditor.css'; const app = createApp(App); app.config.globalProperties.$WangEditor = WangEditor; // 挂载编辑器到全局 app.mount('#app'); ``` 3. 在组件中使用 WangEditor。 ```vue <template> <div class="editor-wrapper"> <div ref="editorRef"></div> </div> </template> <script lang="ts"> import { defineComponent, onMounted, ref } from 'vue'; export default defineComponent({ name: 'Editor', setup() { const editorRef = ref<HTMLDivElement>(); onMounted(() => { const editor = new (window as any).$WangEditor(editorRef.value); editor.create(); }); return { editorRef, }; }, }); </script> <style lang="scss"> .editor-wrapper { height: 400px; .w-e-text-container { height: 100%; } } </style> ``` 在 `onMounted` 钩子函数中,使用 `new (window as any).$WangEditor` 来创建编辑器实例,并传入编辑器容器的 DOM 节点。调用 `editor.create()` 方法来创建编辑器。 注意:由于 WangEditor 的类型定义文件并不完善,因此可以在 `tsconfig.json` 中添加以下配置来避免类型检查报错。 ```json { "compilerOptions": { "skipLibCheck": true } } ``` 这样,就可以在 Vue3 + Vite3 + Typescript 中使用 WangEditor 编辑器了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值