一、在styles文件夹里新建一个globalstyle.scss
二、在App.vue引入
import './styles/globalstyle.scss'
三、在globalstyle.scss定义变量
:root {
--primary-color: #1890ff; // 默认主题颜色
--background-color: #fafafa; // 背景颜色
--text-color: #333; // 字体颜色
}
四、在Vue组件中使用样式变量,使用CSS属性var()来引用
div { background-color: var( --primary-color);}
五、点击进行主题切换
1、创建一个主题切换方法,使用Vue的计算属性访问样式变量。使用Vue的watch选项监视主题变量的更改。
data() {
return {
currentTheme: "default" // 默认主题
};
},
computed: {
primaryColor() {
const themes = {
default: "#1890ff",
red: "#f5222d",
};
return themes[this.currentTheme] || themes.default;
}
},
watch: {
currentTheme() {
document.documentElement.style.setProperty(
"--primary-color",
this.primaryColor
);
}
},
methods: {
switchTheme(theme) {
this.currentTheme = theme;
}
}
2、在Vue中使用切换主题功能。您可以创建一个按钮或下拉菜单来切换主题,并在每个视图组件中使用样式变量。
<button @click="switchTheme('default')">Default Theme</button>
<button @click="switchTheme('red')">Red Theme</button>