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

vue动态样式

作者:迷失未来   发布日期:2025-10-30   浏览:19

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

解释说明

  1. <template> 部分:

    • 使用了 :class:style 绑定来动态设置类名和内联样式。
    • :class="dynamicClass" 动态绑定类名,通过计算属性 dynamicClass 来决定是否应用 activetext-danger 类。
    • :style="dynamicStyle" 动态绑定内联样式,直接使用对象形式定义样式属性。
  2. <script> 部分:

    • data() 中定义了两个布尔值 isActiveerror,以及一个包含内联样式的对象 dynamicStyle
    • computed 中定义了 dynamicClass 计算属性,根据 isActiveerror 的值返回相应的类名对象。
  3. <style> 部分:

    • 定义了 .active.text-danger 类的样式。
    • .active 类设置了背景颜色为绿色。
    • .text-danger 类设置了文字颜色为红色。

这样,当 isActivetrue 时,元素会应用 active 类,当 errortrue 时,元素会应用 text-danger 类。同时,dynamicStyle 对象中的样式也会被应用到元素上。

上一篇:vue 随机数

下一篇:vue组件传值

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue3 router传参

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

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

Laravel 中文站