uniapp 样式切换
uniapp 样式切换方法
在uniapp中实现样式切换可以通过多种方式,以下是常见的几种方法:
动态绑定class
通过数据绑定动态切换class,适合简单的样式切换场景。在模板中使用:class绑定一个对象或数组,根据条件动态切换样式类名。
<template>
<view :class="{ active: isActive, 'text-danger': hasError }">动态class</view>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
}
}
}
</script>
<style>
.active {
background-color: blue;
}
.text-danger {
color: red;
}
</style>
条件渲染样式
使用v-if或v-show控制不同样式元素的显示与隐藏。适合需要完全切换不同布局或样式的场景。
<template>
<view v-if="isDayMode" class="day-mode">日间模式</view>
<view v-else class="night-mode">夜间模式</view>
</template>
使用计算属性
通过计算属性返回动态样式对象,适合需要复杂逻辑判断的场景。
<template>
<view :style="computedStyle">计算属性样式</view>
</template>
<script>
export default {
data() {
return {
isActive: true,
activeColor: 'red'
}
},
computed: {
computedStyle() {
return {
color: this.isActive ? this.activeColor : 'gray',
fontSize: '14px'
}
}
}
}
</script>
主题切换实现
对于完整的主题切换功能,可以通过CSS变量和全局状态管理实现。
定义全局CSS变量:
/* common.css */
:root {
--primary-color: #007AFF;
--bg-color: #FFFFFF;
}
.dark-theme {
--primary-color: #0A84FF;
--bg-color: #1C1C1E;
}
在组件中使用:
<template>
<view class="container" @click="toggleTheme">切换主题</view>
</template>
<script>
export default {
methods: {
toggleTheme() {
const isDark = !this.isDark
this.isDark = isDark
if (isDark) {
document.documentElement.classList.add('dark-theme')
} else {
document.documentElement.classList.remove('dark-theme')
}
}
}
}
</script>
<style>
.container {
background-color: var(--bg-color);
color: var(--primary-color);
}
</style>
使用SCSS/SASS变量
通过预处理器变量实现主题管理,需要配合构建工具使用。
$theme-colors: (
light: (
primary: #007AFF,
bg: #FFFFFF
),
dark: (
primary: #0A84FF,
bg: #1C1C1E
)
);
@mixin theme($theme) {
$colors: map-get($theme-colors, $theme);
.text-primary {
color: map-get($colors, primary);
}
.bg-primary {
background-color: map-get($colors, bg);
}
}
.light-theme {
@include theme(light);
}
.dark-theme {
@include theme(dark);
}
全局状态管理
对于大型应用,可以使用Vuex或Pinia管理主题状态,实现全应用范围内的样式切换。
// store/theme.js
export default {
state: {
currentTheme: 'light'
},
mutations: {
setTheme(state, theme) {
state.currentTheme = theme
}
},
actions: {
toggleTheme({ commit, state }) {
const newTheme = state.currentTheme === 'light' ? 'dark' : 'light'
commit('setTheme', newTheme)
}
}
}
在组件中使用:
<template>
<view :class="[currentTheme + '-theme']">
<button @click="toggleTheme">切换主题</button>
</view>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState(['currentTheme'])
},
methods: {
...mapActions(['toggleTheme'])
}
}
</script>
以上方法可以根据实际需求选择使用,简单场景使用动态class或style即可,复杂主题系统建议采用CSS变量配合状态管理实现。







