You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Vue.js实现点击按钮切换网站整体主题功能

实现方案

你可以基于现有代码稍作调整即可实现全局主题切换,核心思路是把主题类挂载到<body>元素上,而非单独的方块元素:

调整说明

  • 用单个变量存储当前激活的主题,无需维护多个布尔值,也天然实现主题互斥的效果
  • 监听主题变量变化,动态给<body>添加/移除主题类
  • 全局样式直接关联body的主题类,即可实现全站样式切换
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<style>
#app {
  display: flex;
  justify-content: space-around;
}

.demo {
  width: 100px;
  height: 100px;
  background-color: grey;
  cursor: pointer;
}

/* 定义主题对应的全局样式,可按需扩展更多规则 */
body.theme-red {
  background-color: #ffecec;
  color: #a30000;
}
body.theme-green {
  background-color: #ecffec;
  color: #006600;
}
body.theme-blue {
  background-color: #ececff;
  color: #0000a3;
}

/* 方块激活样式 */
.demo.active-red {
  background-color: red;
}
.demo.active-green {
  background-color: green;
}
.demo.active-blue {
  background-color: blue;
}
</style>

<div id="app">
  <div class="demo" :class="{'active-red': currentTheme === 'red'}" @click="switchTheme('red')"></div>
  <div class="demo" :class="{'active-green': currentTheme === 'green'}" @click="switchTheme('green')"></div>
  <div class="demo" :class="{'active-blue': currentTheme === 'blue'}" @click="switchTheme('blue')"></div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    currentTheme: '' // 存储当前激活的主题,空值代表默认主题
  },
  watch: {
    // 监听主题变化,动态修改body的类
    currentTheme(newVal, oldVal) {
      const bodyEl = document.body
      // 先移除旧的主题类
      if (oldVal) {
        bodyEl.classList.remove(`theme-${oldVal}`)
      }
      // 添加新的主题类
      if (newVal) {
        bodyEl.classList.add(`theme-${newVal}`)
      }
    }
  },
  methods: {
    switchTheme(themeName) {
      // 如果点击的是当前已激活的主题,就清空回到默认主题
      this.currentTheme = this.currentTheme === themeName ? '' : themeName
    }
  }
})
</script>

后续如果要拓展更多主题样式,只需要在CSS里新增body.theme-xxx的相关样式规则即可,不需要修改JS逻辑。

内容的提问来源于stack exchange,提问作者FrancoFranco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:24:01