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