1. 简介

本小节我们将介绍 Vue 中如何动态绑定样式。包括 Class 的绑定、内联样式 Style 的绑定。掌握样式绑定的多种形式是其中的重点难点。同学们可以在学完本小节之后对样式的绑定方式加以总结,再通过反复的练习来加深印象。

2. 慕课解释

操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是属性,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。 ---- 官方定义

通过 v-bind 指令给 DOM 元素动态绑定 Class 和 Style,一般用于根据不同数据状态切换元素样式的场景下。

2.绑定元素的 Class

我们可以通过数组和对象的两种形式绑定元素的 Class。

2.1 对象

2.1.1 对象语法

通过传给 v-bind:class 一个对象,以动态地切换 class:

<div v-bind:class="{ show: isShow }"></div>

代码解释:
上面的语法表示 show 这个 class 存在与否将取决于数据属性 isShow 是否为真值。

具体示例:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>
  .hide {
    display: none;
  }
</style>
<body>
  <div id="app"> 
    <div v-bind:class="{hide: isHide}">Hello !</div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
  	isHide: true
  },
})
//vm.isHide = true
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

代码解释:
HTML 代码第 2 行,我们给 div 绑定样式,当 isHide 为真值时, 其渲染结果为 <div class="hide"></div>,否则 <div></div>
打开控制台,修改 vm.isHide 的值可以动态改变页面效果。

2.1.2 与普通的 class 属性共存

此外,v-bind:class 指令也可以与普通的 class 属性共存。
语法:<div class ="defaultClass" v-bind:class="{ classA: isA,classB:isB }">

当有如下模板:

<div
  class="defaultClass"
  v-bind:class="{ show: isShow, 'text-danger': hasError }"
></div>

和如下 data:

data: {
  isShow: true,
  hasError: false
}

结果渲染为:

<div class="defaultClass active"></div>

代码解释:
isShow 或者 hasError 变化时,class 列表将相应地更新。

例如,如果 hasError 的值为 trueisShow 的值为 true,class 列表将变为 "defaultClass show text-danger"

例如,如果 hasError 的值为 trueisShow 的值为 false,class 列表将变为 "defaultClass text-danger"

在之前介绍的案例中,我们将绑定的数据对象内联定义在模板里, 这样显得比较繁琐。其实,我们可以统一定义在一个 classObject 中:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div class="defaultClass" v-bind:class="classObject">Hello !</div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
  	classObject: {
      show: true,
      'text-danger': false
    }
  },
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

结果渲染为:

<div class="defaultClass show"></div>

代码解释:
HTML 代码中,我们首先给 div 一个固定样式 defaultClass, 然后通过 classObject 给 div 绑定样式。
JS 代码 第 6-9 行,我们定义了数据 classObject,它有两个属性:1. 属性 show,值为 true,2. 属性 text-danger,值为 false。所以,最后页面渲染的效果是:<div class="defaultClass show"></div>

2.1.3 利用计算属性绑定样式

<div v-bind:class="classObject"></div>

我们也可以在这里绑定一个返回对象的计算属性。这是一个常用且强大的模式:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div v-bind:class="classObject"></div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  computed: {
    classObject: function () {
      return {
        show: true,
        'text-danger': false
      }
    }
  }
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

结果渲染为:

<div class="defaultClass show"></div>

代码解释:
HTML 代码中,我们通过 classObject 给 div 绑定样式。
JS 代码 第 6-11 行,我们定义了计算属性 classObject,它返回一个对象,该对象有两个属性:1. 属性 show,值为 true,2. 属性 text-danger,值为 false。所以,最后页面渲染的效果是:<div class="show"></div>

2.2 数组语法

我们可以把一个数组传给 v-bind:class,以应用一个 class 列表:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div v-bind:class="[classA, classB]">Hello !</div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
  	classA: 'classA',
    classB: 'classB1 classB2'
  },
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

渲染为:

<div class="classA classB1 classB2"></div>

代码解释:
在 HTML 代码中,我们通过数组给 div 绑定样式,数组中有 classA 和 classB 两个值。
在 JS 代码第 6-7 行定义了 classA 和 classB 两个字符串,它的格式和元素 class 的格式相同,不同的样式类之间以空格相隔。

如果你也想根据条件切换列表中的 class,可以用三元表达式:

<div v-bind:class="[isShow ? showClass : '', classB]"></div>

这样写将始终添加 classB 的样式,但是只有在 isShow 为真时才添加 showClass

不过,当有多个条件 class 时这样写有些繁琐。所以在数组语法中也可以使用对象的形式来表达数组中的某一项:

<div v-bind:class="[{ showClass: isShow }, classB]"></div>

代码解释:
在 HTML 中,div 绑定一个样式数组,数组第一项是一个对象表达式 { showClass: isShow }。当 isShow 为 true 时样式最终绑定为:<div v-bind:class="[showClass, classB]"></div>;当 isShow 为 false 时样式最终绑定为:<div v-bind:class="[classB]"></div>

3. 绑定内联样式

和 Class 的绑定一样,Style 的绑定同样可以通过数组和对象的两种形式。

3.1 对象语法

v-bind:style 的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象。CSS 属性名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div v-bind:style="{ backgroundColor: backgroundColor, width: width + 'px' }"></div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
    backgroundColor: 'red',
    width: 300
  }
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

渲染为:

<div style =" background-color:red;width: 300px"></div>

代码解释:
在 HTML 代码中,我们给 div 绑定 background-color 和 width 两个内联样式,它们的值在 data 中定义。

在模板中写较为复杂的表达式语法显得比较繁琐,通常直接绑定到一个样式对象更好,这会让模板显得更加清晰:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div v-bind:style="styleObject"></div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
  	styleObject: {
      "background-color": 'red',
      width: '300px'
    }
  },
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

渲染为:

<div style ="background-color:red;width: 300px"></div>

代码解释:
在 HTML 代码中,我们给 div 绑定数据 styleObject,它们的值在 data 中定义。

3.2 数组语法

v-bind:style 的数组语法可以将多个样式对象应用到同一个元素上:

实例演示
预览 复制
复制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"> 
    <div v-bind:style="[stylesA, stylesB]"></div>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
 var vm = new Vue({
	el: '#app',
  data: {
    stylesA: {
      "background-color": 'red',
      width: '300px'
    },
    stylesB: {
      color: '#fff',
      height: '300px'
    }
  }
})
</script>
</html>

运行案例 点击 "运行案例" 可查看在线运行效果

渲染为:

<div style ="background-color:red;width: 300px;color:#fff;height:300px"></div>

4. 小结

本小节我们学习了如何通过v-bind来动态绑定样式。主要有以下知识点:

  • 通过 v-bind:class 动态绑定元素的 Class;
  • v-bind:style 动态绑定元素的内联样式;
  • 如果通过数组和对象的形式给 v-bind:class 和 v-bind:style 赋值。