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

vue :class 动态绑定样式

作者:Cold—blooded凉薄   发布日期:2025-08-17   浏览:27

<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>

解释说明

  1. <template> 部分:

    • 使用 :class 指令来动态绑定 classObject 计算属性,该属性返回一个对象,用于控制类的添加或移除。
  2. <script> 部分:

    • data() 函数中定义了两个布尔值变量 isActiveerror,用于控制样式的显示。
    • computed 中定义了 classObject 计算属性,它返回一个对象。根据 isActiveerror 的值,决定是否应用对应的 CSS 类名。
  3. <style> 部分:

    • 定义了两个样式类 .active.text-danger,分别设置了背景颜色和文字颜色。

这样,当 isActivetrue 时,会应用 .active 样式;当 errortrue 时,会应用 .text-danger 样式。

上一篇:antd vue3

下一篇:vue3 mixins

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

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

Laravel 中文站