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

vue 动态class

作者:断念已残   发布日期:2025-09-04   浏览:46

<template>
  <div :class="dynamicClass">Hello World</div>
</template>

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

<style>
.active {
  font-weight: bold;
}

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

解释说明:

  • :class 绑定:通过 :class 指令可以动态地绑定一个对象或数组到元素的 class 属性上。
  • data 中定义了两个布尔值 isActivehasError,用于控制类名的添加。
  • computed 中定义了 dynamicClass 计算属性,返回一个对象。这个对象的键是类名,值是布尔表达式。如果布尔表达式的值为 true,则对应的类名会被添加到元素上。
  • 样式部分定义了 .active.text-danger 类,分别用于加粗字体和设置红色文本颜色。

如果你需要更复杂的动态类绑定,可以根据实际需求调整 datacomputed 部分的内容。

上一篇:vue foreach

下一篇:vue 路由

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

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

Laravel 中文站