Vue语法基础三(样式绑定)
Vue绑定样式有绑定class和绑定style两种方式,这两种方式都有对象语法和数组语法。
一、class绑定
1.1 对象语法
使用js对象的方式,也就是key-value的方式,给元素的class属性绑定样式,其中key是样式,value控制key样式是否有效,value是个布尔值。
<style> div div { width: 100px; height: 100px; } .active { background-color: green; } style> <div id="app"> <div :class="{active: isActive}">div> <button @click="chgStyle">切换背景色button> div> <script> let vm = new Vue({ el: '#app', data: { isActive: true, }, methods: { chgStyle() { this.isActive = !this.isActive; } } }) script>
js对象中可以放置多个样式,如下:
<style> div div { width: 100px; height: 100px; } .active { background-color: green; } .border { border: 2px solid red; } style> <div id="app"> <div :class="{active: isActive, border: hasBorder}">div> <button @click="chgStyle">切换背景色button> <button @click="chgBorder">切换边框button> div> <script> let vm = new Vue({ el: '#app', data: { isActive: true, hasBorder: false }, methods: { chgStyle() { this.isActive = !this.isActive; }, chgBorder() { this.hasBorder = !this.hasBorder } } }) script>
这样就可以同时控制两个样式的切换,如果有更多样式,同理。
1.2 数组语法
给class属性绑定的值也可以是个数组,数组中的元素既可以是data中的变量,也可以直接放类名(字符串形式)。
<style> div div { width: 100px; height: 100px; } .color { background-color: green; } .border { border: 1px solid red; } style> <div id="app"> <div :class="[bgClass, 'border']">class数组语法div> <button @click="handle">切换button> div> <script> let vm = new Vue({ el: '#app', data: { bgClass: 'color', }, methods: { handle() { this.bgClass = '' } } }) script>
点击切换按钮,可以将背景样式置空。
二、style绑定
2.1 对象语法
绑定style时的对象语法,跟内联样式的写法一样,只是css值部分采用了变量来替代。对照绑定class时的对象语法,那是定义好一个内部样式,用value部分来控制内部样式是否有效。
<div id="app"> <div :style="{color: color, fontSize: fontSize + 'px'}">style对象语法div> <button @click="bigger">字号变大button> div> <script> let vm = new Vue({ el: '#app', data: { color: 'red', fontSize: 10 }, methods: { bigger() { this.fontSize = this.fontSize + 5 } } }) script>
2.2 数组语法
style的数组语法跟class的数组语法稍有不同,style数组语法是通过变量的形式引入定义在data区的样式,并且满足css的样式层叠规则。
<div id="app"> <div :style="[baseStyle, overrideStyle]">style数组语法div> <button @click="handle">切换button> div> <script> let vm = new Vue({ el: '#app', data: { baseStyle: { width: '200px', height: '200px', border: '1px red solid' }, overrideStyle: { width: '400px', border: '2px blue dotted' } }, methods: { handle() { this.overrideStyle = '' } } }) script>
因为发生了样式层叠,起先表现为一个宽400高200的虚线蓝框,当我们点击切换按钮时,overrideStyle被置空,这时候只有baseStyle样式生效,就变成了一个宽200高200的实线红框。
总结一下:
class的对象语法和style的对象语法不同,前者用布尔值控制样式是否生效,后者跟css写法一样。
class的数据语法和style的数组语法稍有差异,前者通过变量的值去引入内部样式或者直接用字符串引入内部样式,后者只能通过变量去引入内部样式,并且内部样式通过对象的形式定义在数据区。
PS:本系列文章同步更新于资浅码农的公众号