vue 实现样式的切换
动态类名绑定
通过v-bind:class(简写:class)实现动态类名切换,适用于基于状态切换样式。类名可以是对象或数组形式。
<template>
<div :class="{ 'active': isActive, 'error': hasError }"></div>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
}
}
}
</script>
对象语法中,键为类名,值为布尔值决定是否应用。数组语法允许同时绑定多个类名:
<div :class="[activeClass, errorClass]"></div>
条件样式渲染
使用计算属性动态生成类名或样式对象,适合复杂逻辑判断场景。

<template>
<div :class="computedClass"></div>
</template>
<script>
export default {
data() {
return { isActive: true }
},
computed: {
computedClass() {
return {
'active': this.isActive,
'text-bold': this.isActive
}
}
}
}
</script>
内联样式绑定
通过:style绑定动态样式对象,适用于需要实时计算的样式属性。
<template>
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
</template>
<script>
export default {
data() {
return {
activeColor: 'red',
fontSize: 14
}
}
}
</script>
切换主题实现
结合CSS变量和Vue响应式数据实现主题切换,适合全局样式变更。

<template>
<div :style="themeStyle">
<button @click="toggleTheme">切换主题</button>
</div>
</template>
<script>
export default {
data() {
return {
isDark: false,
lightTheme: {
'--bg-color': '#ffffff',
'--text-color': '#333333'
},
darkTheme: {
'--bg-color': '#222222',
'--text-color': '#ffffff'
}
}
},
computed: {
themeStyle() {
return this.isDark ? this.darkTheme : this.lightTheme
}
},
methods: {
toggleTheme() {
this.isDark = !this.isDark
}
}
}
</script>
<style>
div {
background-color: var(--bg-color);
color: var(--text-color);
}
</style>
第三方库集成
使用vue-class-binding等库增强类名绑定功能,提供更灵活的语法糖。
npm install vue-class-binding
<template>
<div :class="$class.bind({ active: isActive }, 'base-class')"></div>
</template>
动画过渡效果
结合transition组件实现样式切换时的动画过渡。
<template>
<transition name="fade">
<div v-if="show" :class="currentClass"></div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






