Vue.js中class与style的增强绑定如何实现
在web前端应用中,操作元素的class列表的内联样式style是数据绑定style是数据绑定的一个常见需求,因为它们都是attribute,所有可以用v-bind处理它们,但若样式复杂,则需要书写长串的样式代码,这样一来,字符串拼接就比较麻烦。因此,在将v-bind用于class和style时,Vue.js做了专门的增强,表达式结果的类型除了字符串之外,还可以是对象或数组。
一、v-bind绑定class属性
若想使用类样式(即以类名定义元素的样式,类样式一般以"."号开头命令),可以通过v-bind指令绑定class属性实现:
(1)绑定class样式,字符串写法
适用于:样式的类名不确定,需要动态指定
{{name}}
css样式:
.happy {
border: 4px solid red;
background-color: rgba(255, 255, 0, 0.644);
background: linear-gradient(30deg, yellow, pink, orange);
}
.sad {
border: 4px dashed rgb(2, 197, 2);
background-color: gray;
}
.normal {
background-color: skyblue;
}执行结果:

(2)绑定class样式,数组写法
适用于:要绑定的样式个数不确定,名字也不确定
{{name}}
css样式:
.text_1 {
background-color: yellowgreen;
}
.text_2 {
font-size: 30px;
text-shadow: 2px 2px 10px red;
}
.text_3 {
border-radius: 20px;
}执行结果:

(3)绑定class样式,对象写法
适用于:要绑定的样式个数和名字也确定,需要动态显示
{{name}}
css样式:
.text_1 {
background-color: yellowgreen;
}
.text_2 {
font-size: 30px;
text-shadow: 2px 2px 10px red;
}
.text_3 {
border-radius: 20px;
}执行结果:

二、v-bind绑定内联样式style
通过内联(style)绑定给DOM元素示例:
(1)绑定style样式---对象形式
绑定style样式----对象形式
{{name}}
执行结果:

(2)绑定style样式---数组写法
绑定style样式----数组写法
{{name}}
执行结果:
