Vue 动态样式与动态类名

189 阅读2分钟

数据绑定的一个常见需求场景是操纵元素的 CSS class 列表和内联样式。因为 class 和 style 都是 attribute,我们可以和其他 attribute 一样使用 v-bind 将它们和动态的字符串绑定。但是,在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的。因此,Vue 专门为 class 和 style 的 v-bind 用法提供了特殊的功能增强。除了字符串外,表达式的值也可以是对象或数组。

HTML 中使用 styleclass

在 HTML 标签我们中通过 style 属性和 class 属性来设置标签的行内样式及类名。

<div class='container' style='width: 100px; height: 100px;'></div>
.container {
  fonst-size: 14px;
  color: #000;
}

但是如果我们想要动态的控制行内的样式及类名就没有那么容易了。

Vue 的动态样式与动态类名

在 Vue 中我们可以使用属性绑定来动态控制 HTML 中的 style 属性和 class 属性。

动态样式

绑定对象

<!-- 样式名推荐使用驼峰格式 -->
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

<!-- 也支持 kebab-cased 形式的 -->
<div :style="{ color: activeColor, 'font-size': fontSize + 'px' }"></div>

<!-- 绑定样式对象 -->
<div :style="styleObj"></div>
// 定义样式变量
const activeColor = 'red'
const fontSize = 30

// 定义样式对象
const styleObj = {
  color: 'red',
  fontSize: '30px'
}

绑定数组

<!-- 绑定多个样式对象的数组 -->
<div :style="[styleObj1, styleObj2]"></div>
// 定义样式对象
const styleObj1 = {
  color: 'red',
  fontSize: '30px'
}
const styleObj2 = {
  backgroundColor: 'red',
  width: '100px'
}

动态类名

绑定对象

<!-- 控制类名是否存在 -->
<div :class="{ container: true, info: false }"></div>
<!-- 渲染的结果是 -->
<div class="container"></div>

绑定的对象的属性值可以是一个变量或者表达式,这样就可以动态的切换标签的 class

// 定义变量
const hasContainer = true
const hasInfo = false

let a = 1
// 定义表达式
const hasContainer = a > 0
const hasInfo = a < 0
<div :class="{ container: hasContainer, info: hasInfo }"></div>
<!-- 渲染的结果是 -->
<div class="container"></div>

绑定类名对象

<!-- 绑定类名对象 -->
<div :class="classObj"></div>
<!-- 渲染的结果是 -->
<div class="container"></div>
// 定义类名对象
const classObj = {
  container: true,
  info: false
}