<template>
<div :class="dynamicClass" :style="dynamicStyle">
这是一个使用动态样式的Vue组件
</div>
</template>
<script>
export default {
data() {
return {
isActive: true,
error: false,
dynamicStyles: {
color: 'blue',
fontSize: '16px'
}
};
},
computed: {
dynamicClass() {
return {
active: this.isActive,
'text-danger': this.error
};
},
dynamicStyle() {
return {
color: this.dynamicStyles.color,
fontSize: this.dynamicStyles.fontSize
};
}
}
};
</script>
<style>
.active {
background-color: green;
}
.text-danger {
color: red;
}
</style>
动态类名 (:class):
v-bind:class 或简写 :class 绑定一个对象,根据 data 中的属性值来决定是否应用某个类。dynamicClass 是一个计算属性,它返回一个对象。如果 isActive 为 true,则应用 active 类;如果 error 为 true,则应用 text-danger 类。动态样式 (:style):
v-bind:style 或简写 :style 绑定一个对象,直接设置内联样式。dynamicStyle 是一个计算属性,它返回一个对象,包含 color 和 fontSize 样式属性。样式定义:
<style> 标签中定义了两个类:active 和 text-danger,分别设置了背景颜色和文本颜色。通过这种方式,你可以根据数据的变化动态地应用类名和样式。
上一篇:vue async
下一篇:vite+vue+ts
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站