webveuje/vue/class和style绑定.md
2020-12-23 10:29:16 +08:00

166 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# class 和 style绑定
### 绑定HTML class
- 对象语法
- 给v-bind:class 传入一个对象 来动态切换class
v-bind:class="{类名:判断条件}"
```
<div v-bind:class="{ active: isActive }"></div>
```
> 表示active这个class是否存在 取决于isActive 的值转化过后是否为true
- 传入更多字段来切换多个class
```
<div
v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
```
附带如下 data
```
data: {
isActive: true,
hasError: false
}
```
元素渲染结果为:
```
<div class="active"></div>
```
> 如果data 中的hasError的值变成 true
>
> 元素的渲染结果为:
>
> ```
> <div class="active text-danger"></div>
> ```
- v-bind:class 可以和元素上普通的class属性并存
```
<div
class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
```
附带如下data:
```
data: {
isActive: true,
hasError: false
}
```
元素的渲染结果为:
```
<div class="static active"></div>
```
- 数组语法
- 可以把一个数组传给 v-bind:class
v-bind:class="[第一个类名, 第二个类名]"
```
<div v-bind:class="[activeClass, errorClass]"></div>
```
```
data: {
activeClass: 'active',
errorClass: 'text-danger'
}
```
渲染结果为:
```
<div class="active text-danger"></div>
```
- 在数组中用对象语法
```
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
```
### 绑定内联样式
- 对象语法
- 用javascript 对象表达css属性不推荐
v-bind:style="{css属性名: data中定义的属性值}"
示例:
```
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
```
附data:
```
data: {
activeColor: 'red',
fontSize: 30
}
```
- 直接绑定到一个样式对象上(推荐)
v-bind:style="data中的数据"
```
<div v-bind:style="styleObject"></div>
```
附data
```
data: {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
```
- 绑定多个style对象
```
<div v-bind:style="[static,choose]"></div>
```
```
data: {
static: {
fontSize: '13px'
border:'1px solid red'
},
choose:{
color:'red'
}
}
```