1. The Vue project implements skinning
Method 1: Dynamically modify global CSS variables
1. Define global CSS variables in the global css file or app.vue
<style>
:root{
--theme_bg_color:red
}
</style>
2. Use global CSS variables to define element styles
<style scoped>
.myTitle{
background: var(--theme_bg_color);
}
</style>
3. Switch theme (modify global CSS variables)
changeTheme() {
document.documentElement.style.setProperty("--theme_bg_color","green");
}
The effect demo code is as follows:
<div>
<button @click="changeTheme">换肤</button>
<div class="myTitle">你好</div>
</div>
Method 2: Switch theme CSS files
1. Create multiple sets of theme css files and put them in the css folder of the public folder
public/css/theme_green.css
.bg {
background: green;
}
public/css/theme_red.css
.bg {
background: red;
}
2. Set the default theme (initialization style)
src/App.vue
mounted(){
let link = document.createElement('link');
link.type = 'text/css';
link.id = "theme";
link.rel = 'stylesheet';
link.href = './css/theme_red.css';
document.getElementsByTagName("head")[0].appendChild(link);
},
3. Switch theme
changeTheme(){
document.getElementById('theme').href = './css/theme_green.css'
}
The effect demo code is as follows:
<div>
<button @click="changeTheme">换肤</button>
<div class="bg">你好</div>
</div>
Method 3: Switch top-level CSS class names
Need to use css preprocessor, here is sass as an example
1. Create a new theme style file
src/assets/styles/theme.scss
.theme_red{
.head{
background: red;
}
}
.theme_green{
.head{
background: green;
}
}
2. Import theme style files globally
src/main.js
// 全局主题样式
import './assets/styles/theme.scss'
3. Set the default theme (initialization style)
src/App.vue
mounted() {
document.getElementById('app').setAttribute('class', 'theme_red')
},
4. Switch theme
changeTheme() {
document.getElementById('app').setAttribute('class', 'theme_green')
}
The effect demo code is as follows:
<div>
<button @click="changeTheme">换肤</button>
<div class="head">你好</div>
</div>