vue实现动态css
Vue 实现动态 CSS 的方法
使用 :style 绑定内联样式
通过 :style 绑定对象或数组,可以动态修改元素的样式。对象中的属性名可以是驼峰式(如 backgroundColor)或短横线分隔(需用引号包裹,如 'background-color')。
<template>
<div :style="{ color: textColor, fontSize: fontSize + 'px' }">动态样式</div>
</template>
<script>
export default {
data() {
return {
textColor: 'red',
fontSize: 16
};
}
};
</script>
使用 :class 绑定动态类名
通过 :class 绑定对象或数组,可以动态切换类名。对象语法中,类名是否生效取决于值的布尔值。
<template>
<div :class="{ active: isActive, 'text-danger': hasError }">动态类名</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
};
}
};
</script>
使用计算属性生成样式或类名
对于复杂的动态样式逻辑,可以使用计算属性返回样式对象或类名对象/数组。
<template>
<div :style="computedStyle">计算属性样式</div>
<div :class="computedClasses">计算属性类名</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
error: null
};
},
computed: {
computedStyle() {
return {
color: this.error ? 'red' : 'green',
fontWeight: this.isActive ? 'bold' : 'normal'
};
},
computedClasses() {
return {
active: this.isActive,
'text-danger': this.error
};
}
}
};
</script>
使用 CSS 变量(Vue 3 推荐)
Vue 3 支持在模板中直接绑定 CSS 变量,实现更灵活的动态样式。
<template>
<div :style="{'--text-color': textColor}">CSS 变量</div>
</template>
<script>
export default {
data() {
return {
textColor: 'blue'
};
}
};
</script>
<style scoped>
div {
color: var(--text-color);
}
</style>
动态切换样式表
通过动态加载或切换 <style> 标签或外部 CSS 文件,可以实现全局样式切换。
<template>
<button @click="toggleTheme">切换主题</button>
</template>
<script>
export default {
methods: {
toggleTheme() {
const theme = document.getElementById('theme-style');
theme.href = theme.href.includes('dark') ? 'light.css' : 'dark.css';
}
}
};
</script>
注意事项
- 内联样式(
:style)适合少量动态样式,大量样式建议使用类名(:class)。 - 样式优先级:内联样式 > 类名样式,需注意样式覆盖问题。
- Vue 3 的 CSS 变量绑定方式更简洁,推荐在复杂场景中使用。







