uniapp设置不同的主题(Theme)
App.vue:
<style lang="stylus">
@css {
html {
--primary: blue;
--bg-image: url(https://i.loli.net/2020/10/14/gQq96O4DxRVXSKP.jpg);
}
html[data-theme='green'] {
--primary: green;
--bg-image: url(https://i.loli.net/2020/10/14/KdraGmYFC8Wpsz5.jpg);
}
html[data-theme='pink'] {
--primary: pink;
--bg-image: url(https://i.loli.net/2020/10/14/O4wUuGvM3Cdjl16.jpg);
}
}
</style>
组件中使用主题和切换主题:
<template>
<view class="content">
<view class="title"><text>hello world</text></view>
<button type="default" @click="changeTheme(1)">theme blue</button>
<button type="default" @click="changeTheme(2)">theme green</button>
<button type="default" @click="changeTheme(3)">theme pink</button>
</view>
</template>
<script>
export default {
data() {
return {};
},
methods: {
changeTheme(id) {
if (id == 1) {
document.documentElement.removeAttribute('data-theme');
} else if (id == 2) {
document.documentElement.setAttribute('data-theme', 'green');
} else if (id == 3) {
document.documentElement.setAttribute('data-theme', 'pink');
}
}
}
};
</script>
<style lang="stylus">
.content
min-height 100vh
background-image unquote('var(--bg-image)')
.title
color unquote('var(--primary)')
</style>
或者这样
App.vue:
<style lang="stylus">
@css {
.theme {
--primary: red;
}
.theme[data-theme='green'] {
--primary: green;
}
.theme[data-theme='pink'] {
--primary: pink;
}
}
</style>
组件中使用
<template>
<view class="theme content" :data-theme="theme">
<view class="title"><text>hello world</text></view>
<button type="default" @click="changeTheme(1)">theme blue</button>
<button type="default" @click="changeTheme(2)">theme green</button>
<button type="default" @click="changeTheme(3)">theme pink</button>
</view>
</template>
<script>
export default {
data() {
return {
theme: ''
};
},
methods: {
changeTheme(id) {
if (id == 1) {
this.theme = '';
} else if (id == 2) {
this.theme = 'green';
} else if (id == 3) {
this.theme = 'pink';
}
}
}
};
</script>
<style lang="stylus" scoped>
.title
color unquote('var(--primary)')
</style>
See also: