当前位置:首页 > VUE

vue实现主题切换

2026-01-18 11:10:56VUE

Vue 实现主题切换的方法

使用 CSS 变量动态切换主题

定义全局 CSS 变量,通过修改变量值实现主题切换。在 assets/css 目录下创建 theme.css

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

.dark-theme {
  --primary-color: #1e88e5;
  --bg-color: #121212;
  --text-color: #ffffff;
}

在 Vue 组件中通过 document.documentElement.className 切换类名:

methods: {
  toggleTheme() {
    const htmlEl = document.documentElement
    htmlEl.className = htmlEl.className === 'dark-theme' ? '' : 'dark-theme'
  }
}

使用 Vuex 管理主题状态

安装 Vuex 并创建 store 管理主题状态:

vue实现主题切换

// store/index.js
export default new Vuex.Store({
  state: {
    darkTheme: false
  },
  mutations: {
    toggleTheme(state) {
      state.darkTheme = !state.darkTheme
    }
  }
})

在组件中通过计算属性和方法切换主题:

computed: {
  isDarkTheme() {
    return this.$store.state.darkTheme
  }
},
methods: {
  toggleTheme() {
    this.$store.commit('toggleTheme')
    document.documentElement.className = this.isDarkTheme ? 'dark-theme' : ''
  }
}

使用第三方库 vue-theme-switcher

安装主题切换库:

vue实现主题切换

npm install vue-theme-switcher

在 main.js 中引入并配置:

import ThemeSwitcher from 'vue-theme-switcher'
Vue.use(ThemeSwitcher, {
  themes: {
    light: {
      primary: '#42b983',
      background: '#ffffff'
    },
    dark: {
      primary: '#1e88e5',
      background: '#121212'
    }
  }
})

在组件中使用:

this.$theme.set('dark')  // 切换至暗色主题
this.$theme.set('light') // 切换至亮色主题

持久化主题选择

使用 localStorage 保存用户选择的主题:

methods: {
  toggleTheme() {
    const newTheme = this.isDarkTheme ? 'light' : 'dark'
    localStorage.setItem('user-theme', newTheme)
    this.$store.commit('toggleTheme')
    document.documentElement.className = newTheme === 'dark' ? 'dark-theme' : ''
  }
},
created() {
  const savedTheme = localStorage.getItem('user-theme')
  if (savedTheme) {
    this.$store.commit('setTheme', savedTheme === 'dark')
    document.documentElement.className = savedTheme === 'dark' ? 'dark-theme' : ''
  }
}

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

相关文章

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。例…

vue实现加减

vue实现加减

Vue 实现加减功能 在 Vue 中实现加减功能可以通过数据绑定和事件监听来完成。以下是一个简单的实现方法: 模板部分 <template> <div> <…

vue 实现报价

vue 实现报价

Vue 实现报价功能 在 Vue 中实现报价功能通常涉及前端表单交互、数据计算和与后端 API 的通信。以下是实现报价功能的几种常见方法: 表单设计与数据绑定 使用 Vue 的 v-model 指…

vue 实现table

vue 实现table

Vue 实现 Table 的方法 使用原生 HTML 表格 通过 Vue 的 v-for 指令动态渲染表格数据,适合简单表格场景。 <template> <table>…

vue实现ftp

vue实现ftp

Vue 中实现 FTP 功能 Vue 本身是一个前端框架,无法直接操作 FTP 协议(FTP 通常需要后端支持)。以下是两种常见实现方式: 前端与后端配合实现 FTP 前端通过 API 与后端通信,…

vue实现fragment

vue实现fragment

Vue 实现 Fragment 的方法 在 Vue 中,Fragment 允许组件返回多个根节点而不需要包裹一个额外的 DOM 元素。以下是几种实现方式: 使用 Vue 3 的 <templa…