vue2一键换肤

在 Vue 2 中实现一键换肤功能,你可以使用 CSS 变量、动态样式表或 Vuex。以下是一个使用 CSS 变量和 Vuex 的示例:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    theme: 'light',
  },
  mutations: {
    SET_THEME(state, theme) {
      state.theme = theme;
    },
  },
  actions: {
    changeTheme({ commit }, theme) {
      commit('SET_THEME', theme);
    },
  },
});

 

定义 CSS 变量 (custom properties)。在 /src/assets/css/themes.css 中定义两个主题(例如,深色主题和浅色主题):

css:
:root {
  --color-primary: #42b983;
  --color-background: #fff;
  --color-text: #333;
}

.dark-theme {
  --color-primary: #5c6bc0;
  --color-background: #424242;
  --color-text: #cfd8dc;
}

 在 App.vue 中引入 themes.css 并应用主题

<template>
  <div id="app" :class="themeClass">
    <!-- Your app content -->
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['theme']),
    themeClass() {
      return this.theme === 'dark' ? 'dark-theme' : '';
    },
  },
};
</script>

<style>
@import './src/assets/css/themes.css';
</style>

 添加换肤按钮。在 Vue 组件中(如 src/components/SwitchTheme.vue)创建一个按钮,用于在两个主题之间切换:

<template>
  <button @click="switchTheme">Toggle theme</button>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['changeTheme']),
    switchTheme() {
      let newTheme = this.$store.state.theme === 'light' ? 'dark' : 'light';
      this.changeTheme(newTheme);
    },
  },
};
</script>

 在 src/App.vue 中引入刚才创建的组件

<template>
  <div id="app" :class="themeClass">
    <switch-theme></switch-theme>
    <!-- Your app content -->
  </div>
</template>

<script>
import SwitchTheme from './components/SwitchTheme';

export default {
  components: {
    SwitchTheme,
  },
  // ...
};
</script>

 完成这些步骤后,应用程序将包含一个可以切换深色和浅色主题的按钮。你可以根据需要扩展或调整此示例来适应不同的主题和颜色方案。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值