当前位置:首页 > VUE

vue主题切换实现

2026-02-19 09:56:17VUE

实现 Vue 主题切换的方法

使用 CSS 变量动态切换主题

定义全局 CSS 变量,通过修改变量值实现主题切换。在根元素(如 :root)中定义主题相关变量:

:root {
  --primary-color: #42b983;
  --bg-color: #ffffff;
  --text-color: #333;
}

.dark-theme {
  --primary-color: #646cff;
  --bg-color: #242424;
  --text-color: rgba(255, 255, 255, 0.87);
}

在 Vue 组件中通过 document.documentElement.classList 切换主题类:

const toggleTheme = () => {
  document.documentElement.classList.toggle('dark-theme');
};

使用 Vuex/Pinia 管理主题状态

通过状态管理工具存储当前主题,结合计算属性动态应用样式:

// Pinia 示例
import { defineStore } from 'pinia';

export const useThemeStore = defineStore('theme', {
  state: () => ({
    isDark: false
  }),
  actions: {
    toggleTheme() {
      this.isDark = !this.isDark;
      document.documentElement.classList.toggle('dark-theme', this.isDark);
    }
  }
});

结合 Tailwind CSS 实现

配置 tailwind.config.js 启用暗色模式:

module.exports = {
  darkMode: 'class',
  // ...
}

在模板中通过类名切换:

<button @click="toggleTheme">切换主题</button>
<div :class="{ 'dark': isDark }">
  <!-- 内容 -->
</div>

持久化主题选择

使用 localStorage 保存用户选择,避免刷新后重置:

vue主题切换实现

const saveThemePreference = (isDark) => {
  localStorage.setItem('theme', isDark ? 'dark' : 'light');
};

const loadThemePreference = () => {
  return localStorage.getItem('theme') === 'dark';
};

完整组件示例

<template>
  <button @click="toggleTheme">
    {{ isDark ? '浅色模式' : '深色模式' }}
  </button>
</template>

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

const isDark = ref(false);

const toggleTheme = () => {
  isDark.value = !isDark.value;
  document.documentElement.classList.toggle('dark-theme', isDark.value);
  localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
};

onMounted(() => {
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme === 'dark') {
    isDark.value = true;
    document.documentElement.classList.add('dark-theme');
  }
});
</script>

标签: 主题vue
分享给朋友:

相关文章

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <templ…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独立…

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些方…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

vue实现素材

vue实现素材

Vue 实现素材的方法 使用 Vue 组件管理素材 在 Vue 项目中,可以通过组件化的方式管理素材。创建一个专门的组件来加载和显示素材,例如图片、视频或音频文件。组件可以接收素材的路径或 URL 作…