<template>
<div :class="dynamicClass" :style="dynamicStyle">
这是一个使用动态样式的元素
</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
error: false,
dynamicStyle: {
color: 'red',
fontSize: '20px'
}
};
},
computed: {
dynamicClass() {
return {
active: this.isActive,
'text-danger': this.error
};
}
}
};
</script>
<style>
.active {
background-color: green;
}
.text-danger {
color: red;
}
</style>
<template> 部分:
:class 和 :style 绑定来动态设置类名和内联样式。:class="dynamicClass" 动态绑定类名,通过计算属性 dynamicClass 来决定是否应用 active 和 text-danger 类。:style="dynamicStyle" 动态绑定内联样式,直接使用对象形式定义样式属性。<script> 部分:
data() 中定义了两个布尔值 isActive 和 error,以及一个包含内联样式的对象 dynamicStyle。computed 中定义了 dynamicClass 计算属性,根据 isActive 和 error 的值返回相应的类名对象。<style> 部分:
.active 和 .text-danger 类的样式。.active 类设置了背景颜色为绿色。.text-danger 类设置了文字颜色为红色。这样,当 isActive 为 true 时,元素会应用 active 类,当 error 为 true 时,元素会应用 text-danger 类。同时,dynamicStyle 对象中的样式也会被应用到元素上。
上一篇:vue 随机数
下一篇:vue组件传值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站