- 定义主题变量
:root {--primary-color: #314099;--secondary-color: #1E3968;--text-color: #2c44ce;
}[data-theme="红系主题"] {--primary-color: #d74146;--secondary-color: #c20707;--text-color: #db3b3b;
}
- 在组件中使用变量
<template><div class="app" :data-theme="currentTheme"><button @click="toggleTheme">切换主题</button><div class="content">主题色内容</div></div>
</template><script>
export default {data() {return {currentTheme: '蓝系主题'}},methods: {toggleTheme() {this.currentTheme = this.currentTheme === '蓝系主题' ? '红系主题' : '蓝系主题';localStorage.setItem('theme', this.currentTheme); }},mounted() {const savedTheme = localStorage.getItem('theme');if (savedTheme) this.currentTheme = savedTheme;}
}
</script><style lang="scss">
@import '@/styles/themes.scss';.content {color: var(--text-color);background-color: var(--primary-color);padding: 20px;transition: all 0.3s ease;
}
</style>