首页/ 学科题库/ vue/ v-bind动态class与style
vue 实战教程

v-bind动态class与style

2026-05-20 约 6 分钟 juanwangdev

v-bind动态class与style

v-bind 在 class 和 style 绑定上有特殊增强。

绑定 class

对象语法

HTML
<div :class="{ active: isActive, 'text-danger': hasError }"></div>

对象键是类名,值是布尔值。

数组语法

HTML
<div :class="[activeClass, errorClass]"></div>
JavaScript
data() {
  return {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
}

混合使用

HTML
<div :class="[{ active: isActive }, errorClass]"></div>

绑定 style

对象语法

HTML
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

数组语法

HTML
<div :style="[baseStyles, overridingStyles]"></div>

自动前缀

Vue 会自动添加浏览器引擎前缀:

HTML
<div :style="{ transform: 'rotate(45deg)' }"></div>

要点总结

  • class 绑定支持对象和数组语法
  • style 绑定同样支持对象和数组
  • Vue 自动添加 CSS 浏览器前缀
  • 可混合使用多种绑定方式
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 v-html与v-text 下一篇 → 事件处理基础