vue动态绑定class的3种方式对象语法和数组语法

本文详细介绍了在Vue.js中动态绑定class和内联样式的三种方法:对象语法、数组语法及绑定行内样式。通过实例展示了如何使用计算属性实现条件绑定,使样式根据数据变化而变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态绑定class的几种方式

1.对象语法 行内或计算属性

<style>
    .static {
      width: 100px;
      height: 100px;
      background-color: #ccc;
    }
    .orange {
      border: 1px solid orange;
    }
  </style>
</head>
<body>
  <!-- 对象语法 -->
  <!-- <div id="example" class="static" v-bind:class="{'orange': isRipe, 'green': isNotRipe}"></div> -->
  <div id="example" class="static" v-bind:class="haha"></div>
</body>
  // 01class绑定方法1对象语法
  var vm = new Vue({
    el: "#example",
    data: {
      //   isRipe: true,
      //   isNotRipe: false
      age: 4,
      member: 999
    },
    computed: {
      haha: function() {
        return {
          'orange': this.age > 3 ? true : false,
          'green': this.member > 1000 ? true : false
        }
      }
    }
  })

方法2数组语法

 // 数组语法 
  <div id="example" class="static" v-bind:class="[class1, class2]"></div>
  var vm = new Vue({
    el: "#example",
    data: {
      class1: 'orange',
      class2: 'green'
    }
  })

方法3绑定行内样式

  <!-- 对象语法 -->
  // <div id="app" v-bind:style="{color: color, fontSize: fontSize+'px' }">hello world</div> -->
 // <div id="app" v-bind:style="style">hello world</div>
  <div id="app" v-bind:style="haha">hello world</div>
    var vm = new Vue({
      el: '#app',
      data: {
        // color: 'pink',
        // fontSize: 30
        // style: {
        //   color: 'pink',
        //   fontSize: '30px'
        // }
        age: 4,
        member: 9000
      },
      computed: {
        haha : function() {
          return {
            color: this.age >3 ? orange: green,
            fontSize: this.member> 1000 ? '30px' :'10px'
          }
        }
      }
    })

转载于:https://www.cnblogs.com/zhtian/p/10053886.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值