Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue class动态绑定样式

作者:刺眼的男ren   发布日期:2026-01-19   浏览:36

<template>
  <div :class="classObject">我是一个动态绑定样式的元素</div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true,
      error: false
    };
  },
  computed: {
    classObject() {
      return {
        active: this.isActive,
        'text-danger': this.error
      };
    }
  }
};
</script>

<style>
.active {
  background-color: green;
}

.text-danger {
  color: red;
}
</style>

解释说明:

  • :class="classObject":使用 Vue 的 v-bind:class 指令(简写为 :)来动态绑定样式。classObject 是一个计算属性,返回一个对象,对象的键是类名,值是布尔值,表示是否应用该类。
  • data():定义了两个数据属性 isActiveerror,用于控制样式的动态变化。
  • computed:定义了一个计算属性 classObject,根据 isActiveerror 的值返回相应的类名对象。
  • style:定义了两个 CSS 类 .active.text-danger,分别设置背景颜色和文本颜色。

这样,当 isActivetrue 时,元素会应用 active 类;当 errortrue 时,元素会应用 text-danger 类。

上一篇:vue 3.0

下一篇:vue $nexttick

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站