
在 Vue 中,可以使用 v-bind 指令来动态添加 class。v-bind:class 指令可以接受一个对象,对象的 key 是 class 名称,value 是控制 class 是否添加的 布尔值 或 计算属性。
1. 使用对象语法:
```html
```
isActive 为 true 时,div 元素将添加 active 类。
2. 绑定多个 class:
```html
```
isActive 和 hasError 分别控制 active 和 text-danger 两个类的添加。
3. 使用计算属性:
```html
```
```javascript
data: {
isActive: true
hasError: false
}
computed: {
classObject: function () {
return {
active: this.isActive
text-danger: this.hasError
}
}
}
```
classObject 是一个计算属性,根据 isActive 和 hasError 的值返回一个对象,并在模板中使用 v-bind:class 绑定到 div 元素上。
4. 使用数组语法:
```html
```
```javascript
data: {
activeClass: active
errorClass: text-danger
}
```
activeClass 和 errorClass 是 data 中的两个变量,通过数组语法将它们绑定到 div 元素上。
5. 数组语法中使用三元表达式:
```html
```
isActive 为 true 时,添加 activeClass 类;hasError 为 true 时,添加 errorClass 类。
6. 数组语法中使用对象语法:
```html
```
isActive 为 true 时,添加 active 类;errorClass 为一个具有 active 属性的对象,也会根据 isActive 的值来决定是否添加该类。
以上是在 Vue 中使用 v-bind:class 指令实现动态添加 class 的几种方式。通过灵活运用不同的语法,可以根据组件的状态和需求来动态改变 class 的添加。