<template>
<div :class="dynamicClass">
这是一个使用了动态类的 div 元素。
</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
hasError: false
};
},
computed: {
dynamicClass() {
return {
active: this.isActive,
'text-danger': this.hasError
};
}
}
};
</script>
<style>
.active {
background-color: green;
}
.text-danger {
color: red;
}
</style>
:class
绑定:在 Vue 中,你可以使用 :class
来动态绑定 CSS 类。这允许你在运行时根据组件的状态或数据来切换类。dynamicClass
是一个计算属性,它返回一个对象,这个对象的键是类名,值是布尔表达式。如果表达式为 true
,则对应的类会被添加到元素上;否则,类将不会被添加。data
属性:isActive
和 hasError
是两个布尔类型的属性,它们控制着是否应用 active
和 text-danger
类。<style>
标签中定义了 .active
和 .text-danger
类的样式。.active
类会改变背景颜色为绿色,而 .text-danger
类会改变文本颜色为红色。这样,当 isActive
为 true
时,div
元素会有绿色背景;当 hasError
为 true
时,文本颜色会变成红色。
上一篇:vue3跳转页面传递参数
下一篇:vue 获取页面高度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站