Vue动态绑定Class常用的几种方式

第一种:基础用法

Html部分:

<div :class="active">基本用法</div>

Js部分:

data() {

        return {

                active: 'active'

        }

}

 

第二种:三元运算绑定单个 / 数组形式绑定多个Class

Html部分:

<div :class="isBind ? 'active' : ''">三元运算</div>
<div :class="[isBind ? 'active' : '', active]">使用数组</div>

Js部分:

data() {

        return {

                isBind: false,

                active: 'active'

        }

}

 

第三种:计算属性绑定单个或多个Class

Html部分:

<div :class="classObject">使用计算属性</div>

Js部分: 

data() {

        return {

                active: 'active',

                finishData: '2022-10-18 00:00:00'

        }

},

computed: {

        classObject() {

                return {

                        active: this.isBind,

                        'red-color': this.finishData != ''

                }

        }

}

 

第四种:使用函数绑定Class

Html部分:可自定义传参

div :class="bindClass(currDate,finishData)">函数绑定</div> 

Js部分:可处理复杂逻辑

data() {

        return {

                currDate: '2022-10-20 00:00:00',

                finishData: '2022-10-18 00:00:00'

        }

},

methods: {

        // 动态绑定Class

        bindClass(currDate,finishData){

                let classInfo = { redColor: false, active: true }

                if(new Date(finishData).getTime() > new Date(currDate).getTime()){

                        classInfo.redColor = true

                }

                return classInfo

        }

}