- Vue.js企业开发实战
- 千锋教育高教产品研发部编著
- 616字
- 2022-07-28 19:42:48
2.6 class与style样式绑定
在Vue中,经常需要动态地设置元素的CSS样式,我们可以通过v-bind属性绑定,为标签的class属性和style属性动态赋值。
2.6.1 HTML样式绑定
1.数组语法
在Vue中,动态的样式类在v-bind:class中定义,静态的类名写在class样式中。
index.html文件代码如下:

在浏览器中运行的效果如图2.51所示。

图2.51 数组语法渲染
在上面的示例代码中,数组中样式的类名要使用单引号包裹,不然会出错。但是在某些应用场景下,需要使用变量表示类名,在数组中也可以使用这种方式绑定样式。
index.html文件代码如下:

在数组中也可以直接使用对象语法,示例代码如下:

上面代码运行的效果和图2.51所示的效果是相同的。
2.对象语法
在Vue中可以直接使用对象设置样式,对象的属性为样式的类名,其值为Boolean类型,当值为true时显示样式。对象的属性可以带引号,也可以不带引号。
index.html文件代码如下:

上面代码运行的效果和图2.51所示的效果相同。当对象中的属性过多时,如果将所有属性都写在元素上,则标签会显得代码冗余,此时我们可以使用计算属性来解决这个问题。
index.html文件代码如下:

上面代码运行的效果和图2.51所示的效果是相同的。
2.6.2 内联样式绑定
内联样式是将CSS样式编写到元素的style属性中,这种操作方法与设置class样式相同,也可以使用对象为元素进行设置。
index.html文件代码如下:

在浏览器中运行的效果如图2.52所示。

图2.52 style对象语法效果
同样,可以直接绑定一个样式对象属性,这样的代码看起来会更加简洁美观。
index.html文件代码如下:

还可以使用计算属性,返回样式对象,代码如下:

上面示例代码运行的效果和图2.52所示的效果相同。