vue 实现样式切换
动态类名绑定
通过 v-bind:class 或简写 :class 实现动态类名切换,结合计算属性或方法返回类名对象。适用于根据状态切换预定义的 CSS 类。
<template>
<div :class="{ 'active-style': isActive, 'error-style': hasError }"></div>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
}
}
}
</script>
<style>
.active-style { background: blue; }
.error-style { border: 1px solid red; }
</style>
内联样式绑定
使用 v-bind:style 或 :style 直接绑定样式对象,适合需要动态计算的样式值。样式对象中的属性需采用驼峰命名。
<template>
<div :style="styleObject"></div>
</template>
<script>
export default {
data() {
return {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
}
}
</script>
条件渲染样式
通过 v-if/v-show 控制不同样式元素的显示与隐藏。v-show 通过 CSS 的 display 属性切换,v-if 会销毁/重建 DOM 节点。

<template>
<div>
<div v-show="isDay" class="day-mode">日间模式</div>
<div v-show="!isDay" class="night-mode">夜间模式</div>
</div>
</template>
CSS 变量控制
结合 Vue 的响应式数据和 CSS 变量实现动态样式。通过修改根元素的 CSS 变量值全局更新样式。
<template>
<div class="dynamic-color">
<button @click="changeColor">切换主题色</button>
</div>
</template>
<script>
export default {
methods: {
changeColor() {
document.documentElement.style.setProperty('--primary-color', this.isDark ? '#333' : '#f0f');
}
}
}
</script>
<style>
.dynamic-color {
color: var(--primary-color, blue); /* 默认值为 blue */
}
</style>
第三方库集成
使用如 vue-theam-switcher 等插件实现主题切换功能,适合复杂主题管理系统。

import ThemeSwitcher from 'vue-theme-switcher'
Vue.use(ThemeSwitcher)
状态管理配合
在 Vuex 或 Pinia 中存储样式状态,实现跨组件样式同步。通过映射状态或 getters 获取样式配置。
// Pinia 示例
export const useThemeStore = defineStore('theme', {
state: () => ({ isDark: false }),
actions: {
toggleTheme() { this.isDark = !this.isDark }
}
})
响应式布局适配
利用 window.matchMedia() 监听媒体查询变化,结合 Vue 的响应式数据实现自适应样式切换。
mounted() {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
this.isDarkMode = mediaQuery.matches
mediaQuery.addListener(e => {
this.isDarkMode = e.matches
})
}
以上方法可根据具体场景组合使用。动态类名适合离散状态切换,内联样式适合精细控制,CSS 变量适合主题管理,状态管理适合复杂应用,媒体查询适合响应式需求。性能敏感场景建议优先使用 CSS 类名切换而非内联样式。






