Vue3学习笔记:Day4 Class和Style
如何在Vue模板中使用class和style,并且动态的改变
绑定Class
使用v-bind绑定class分为两种语法
- 使用对象绑定
- 使用数组绑定
使用对象绑定
- 直接在模板中定义对象 - 1 
 2
 3
 4- <div 
 class="static"
 :class="{ active: isActive, 'text-danger': hasError }"
 ></div>- 1 
 2
 3
 4
 5
 6- data() { 
 return {
 isActive: true,
 hasError: false
 }
 }类的名字最好使用字符串,有些名称可能会出现错误,但是像active这种也可以
- 对象定义在data中 - 1 - <div :class="classObject"></div> - 1 
 2
 3
 4
 5
 6
 7
 8- data() { 
 return {
 classObject: {
 active: true,
 'text-danger': false
 }
 }
 }
- 但是最常见的还是定义在computed计算属性中 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14- data() { 
 return {
 isActive: true,
 error: null
 }
 },
 computed: {
 classObject() {
 return {
 active: this.isActive && !this.error,
 'text-danger': this.error && this.error.type === 'fatal'
 }
 }
 }- 在计算属性中编写表达式进行计算可以响应,并且有缓存的存在使调用时使用空间换取时间和算力,性能更好 
使用数组绑定
直接从数组中传入类名数组即可渲染,其中类名既可以是变量也可以直接是字符串
| 1 | <div :class="[activeClass, errorClass, 'bg-white']"></div> | 
| 1 | data() { | 
结果为
| 1 | <div class="active text-danger bg-white"></div> | 
在数组中可以使用过三元表达式
| 1 | <div :class="[isActive ? activeClass : '', errorClass]"></div> | 
还可以使用上面对象语法,传入键值对
| 1 | <button :class="['btn','btn-primary',{ 'text-dark': isdark, 'active': isactive}]">Hello {{ user }}</button> | 
绑定Style
同绑定class一样,也有对象和数组两种方法
使用对象绑定
| 1 | <div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> | 
| 1 | data() { | 
也可以将对象写到data中或计算属性computed中
| 1 | <div :style="styleObject"></div> | 
| 1 | data() { | 
更常使用computed
| 1 | const AppData = { | 
使用数组绑定
也可以传入对象数组进行绑定
| 1 | <div :style="[baseStyles, overridingStyles]"></div> | 
绑定Style时的机制
- 对于一些属性在浏览器中需要某些前缀,Vue会在运行时检查多次测试并自动加上 
- 在style对象中可以让某个属性的值等于一个数组,只会渲染最后一个浏览器支持的属性值,如 - 1 
 2
 3
 4
 5- { 
 color: this.textColor,
 fontSize: this.textSize + 'px',
 display: ['box','inline-block','flex']
 }- 结果为 - display: flex- 但如果 - flex变为某个不可使用的属性,如- 1 
 2
 3
 4
 5- { 
 color: this.textColor,
 fontSize: this.textSize + 'px',
 display: ['box','inline-block','aflex']
 }- 则结果为 - display: inline-block