uni-app设置动态样式class的几种写法,分别列举案例
时间: 2023-08-21 21:03:35 浏览: 189
在uni-app中,设置动态样式class有以下几种写法:
1. 对象语法:可以通过在标签上使用v-bind:class指令,并将一个对象作为参数来设置动态样式class。对象语法中,键名为class名称,键值为布尔值,表示是否应用该class样式。例如:
```html
<template>
<div :class="{ 'red': isRed, 'bold': isBold }">Hello world!</div>
</template>
<script>
export default {
data() {
return {
isRed: true,
isBold: false,
};
},
};
</script>
<style>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
```
在上面的例子中,div标签使用对象语法设置了动态样式class。isRed为真,因此会应用'red'样式类;isBold为假,因此不会应用'bold'样式类。
2. 数组语法:可以通过在标签上使用v-bind:class指令,并将一个数组作为参数来设置动态样式class。数组语法中,数组元素为class名称,会依次应用该class样式。例如:
```html
<template>
<div :class="[ 'red', isBold ? 'bold' : '' ]">Hello world!</div>
</template>
<script>
export default {
data() {
return {
isBold: false,
};
},
};
</script>
<style>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
```
在上面的例子中,div标签使用数组语法设置了动态样式class。数组元素为class名称,会依次应用'red'样式类和'bold'样式类(当isBold为真时)。
3. 对象语法配合计算属性:可以在组件中定义计算属性,返回一个对象,再将该对象设置为动态样式class,达到更加灵活的效果。例如:
```html
<template>
<div :class="classObject">Hello world!</div>
</template>
<script>
export default {
data() {
return {
isRed: true,
isBold: false,
};
},
computed: {
classObject() {
return {
'red': this.isRed,
'bold': this.isBold,
};
},
},
};
</script>
<style>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
```
在上面的例子中,div标签通过计算属性classObject来设置动态样式class。classObject返回一个对象,键名为class名称,键值为布尔值,表示是否应用该class样式。isRed为真,因此会应用'red'样式类;isBold为假,因此不会应用'bold'样式类。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)