行业知识
Vue中Class绑定和style绑定的方式
2026-11-18 14:23:17
来源:互联网转载
样式绑定
���据绑定的一个常见需求场景是操纵元素的CSS的class列表和内联样式
()- 因为class和style都是标签属性,我们可以和其他属性一样使用v-bind指令将它们和动态的字符串绑定
- 在处理比较复杂的绑定时,通过拼接生成字符串是麻烦且易出错的, Vue对于class和style的v-bind的值除了字符串外,表达式的值也可以是对象或数组
Class绑定的三种方式
绑定字符串适用场景:如果确定动态绑定的样式个数只有1个,但是名字不确定需要动态指定
.static{ border: 1px solid black; background-color: aquamarine; } .big{ width: 200px; height: 200px; } .small{ width: 100px; height: 100px; }{{msg}}
{{msg}} 变大 变小 {{msg}} const vm = new Vue({ el : '#app', data : { msg : 'Class绑定之字符串形式', c1 : 'small' }, methods: { changeBig(){ this.c1 = 'big' }, changeSmall(){ this.c1 = 'small' } }, })绑定数组适用场景:当绑定的样式个数不确定,并且样式的名字也不确定的时候
().static { border: 1px solid black; width: 100px; height: 100px; } .active { background-color: green; } .text-danger { color: red; }{{msg}}
{{msg}} {{msg}} {{msg}} {{msg}} const vm = new Vue({ el : '#app', data : { msg : 'Class绑定之数组形式', c1 : 'active', c2 : 'text-danger', classArray : ['active', 'text-danger'] } })绑定对象适用场景:样式的个数是固定的,样式的名字也是固定的,但是需要动态的决定样式用还是不用
- 对象中属性的名字必须和样式名一致
.static { border: 1px solid black; width: 100px; height: 100px; } .active { background-color: green; } .text-danger { color: red; }{{msg}}
{{msg}} {{msg}} const vm = new Vue({ el : '#app', data : { msg : 'Class绑定之对象形式', classObj : { // 该对象中属性的名字必须和样式名一致(对象中的属性名都有单引号并且可以省略,但是对于属性名含有划线的单引号不能省略) active : false, 'text-danger' : true } } })style绑定的三种方式
绑定对象时对象的属性名要采用大驼峰的形式,属性值需要用单引号括起来
.static { border: 1px solid black; width: 100px; height: 100px; }{{msg}}
{{msg}} {{msg}} {{msg}} {{msg}} {{msg}} const vm = new Vue({ el : '#app', data : { msg : 'Style绑定', myStyle : 'background-color: gray;', styleObj : { backgroundColor: 'green' }, styleArray : [ {backgroundColor: 'green'}, {color : 'red'} ] } })
- 对象中属性的名字必须和样式名一致
上一篇:服务器怎么同步数据?