当前位置:首页 > 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 管理主题状态:

// 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

安装主题切换库:

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 实现选择季度的几种方法 使用下拉选择框(Select) 在 Vue 中可以通过 v-model 绑定一个下拉选择框来实现季度选择。数据可以预先定义为一个包含季度选项的数组。 <…

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue 实现在线预览

vue 实现在线预览

Vue 实现在线预览的常见方法 使用 iframe 嵌入 通过 iframe 标签可以嵌入多种类型的文件,如 PDF、图片、网页等。需要确保文件地址可访问。 <template>…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &l…

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted…

vue tag实现

vue tag实现

Vue 标签实现方法 在 Vue 中实现标签功能可以通过多种方式完成,常见场景包括动态标签生成、标签输入框、标签管理等。以下是几种典型实现方案: 动态标签列表渲染 使用 v-for 指令渲染标签数组…