vue less实现主题切换
使用 Vue 和 Less 实现主题切换
配置 Less 和变量文件
在 Vue 项目中安装 Less 和 Less-loader:
npm install less less-loader --save-dev
创建一个全局的 Less 变量文件,例如 src/styles/variables.less,定义主题相关的变量:
// 默认主题
@primary-color: #1890ff;
@background-color: #ffffff;
@text-color: #333333;
// 暗色主题
[data-theme="dark"] {
@primary-color: #722ed1;
@background-color: #141414;
@text-color: #f0f0f0;
}
在 Vue 组件中使用 Less 变量
在组件的样式部分引入全局变量文件,并使用定义的变量:
<template>
<div class="example">
<button class="btn">按钮</button>
</div>
</template>
<script>
export default {
name: 'Example'
}
</script>
<style lang="less" scoped>
@import "~@/styles/variables.less";
.example {
background-color: @background-color;
color: @text-color;
}
.btn {
background-color: @primary-color;
color: white;
}
</style>
动态切换主题
通过修改 HTML 元素的 data-theme 属性来切换主题。创建一个主题切换的方法:
<template>
<div id="app">
<button @click="toggleTheme">切换主题</button>
<Example />
</div>
</template>
<script>
import Example from './components/Example.vue'
export default {
name: 'App',
components: {
Example
},
methods: {
toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme')
const newTheme = currentTheme === 'dark' ? null : 'dark'
document.documentElement.setAttribute('data-theme', newTheme)
}
}
}
</script>
持久化主题状态
使用 localStorage 保存用户选择的主题,确保刷新后主题不变:
<script>
export default {
name: 'App',
mounted() {
const savedTheme = localStorage.getItem('theme')
if (savedTheme) {
document.documentElement.setAttribute('data-theme', savedTheme)
}
},
methods: {
toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme')
const newTheme = currentTheme === 'dark' ? null : 'dark'
document.documentElement.setAttribute('data-theme', newTheme)
localStorage.setItem('theme', newTheme)
}
}
}
</script>
使用 CSS 变量增强灵活性
结合 CSS 变量和 Less 变量,提供更灵活的主题控制:
// variables.less
:root {
--primary-color: #1890ff;
--background-color: #ffffff;
--text-color: #333333;
}
[data-theme="dark"] {
--primary-color: #722ed1;
--background-color: #141414;
--text-color: #f0f0f0;
}
@primary-color: var(--primary-color);
@background-color: var(--background-color);
@text-color: var(--text-color);
注意事项
- 确保 Less 变量和 CSS 变量的命名一致,避免混淆。
- 使用
scoped样式时,注意主题变量的作用域问题。 - 在大型项目中,可以考虑使用 Vuex 或 Pinia 管理主题状态。







