DIV CSS 佈局教程網

Vue.js 綁定 class 與 inline style 的完整用法整理
編輯:關於JavaScript     

資料綁定有一類需求特別常見:動態操作元素的 class 清單與行內樣式。這兩者都是 attribute,理論上可以用 v-bind 直接處理,只要算出最終字串就行。但字串拼接既麻煩又容易出錯,因此 Vue.js 在 class 與 style 這兩個 attribute 上特別做了增強:除了字串,綁定結果還可以是物件或陣列。

一、綁定 class

寫法為 v-bind:class,可簡寫成 :class。引號內接受物件字面值、物件參照或陣列。

<div :class="{ active: isActive }"></div>

這裡 { active: isActive } 是物件參數:active 是 class 名稱,isActive 是一個布林值——為真時才把該 class 加上去。

1. 綁定物件字面值

HTML:

<div id="classBind">
  <span :class="{ warning: isWarning, safe: isSafe }" v-on:click="toggle">
    狀態:{{alert}}{{isSafe}}
  </span>
</div>

<script>
var app11 = new Vue({
    el: '#classBind',
    data: {
        isWarning: true,
        alertList: ['紅色警報', '警報解除'],
        alert: ''
    },
    computed: {
        isSafe: function () {
            return !this.isWarning;
        }
    },
    methods: {
        toggle: function () {
            this.isWarning = !this.isWarning;
            this.alert = this.isWarning ? this.alertList[0] : this.alertList[1];
        }
    }
});
</script>

CSS:

.warning { color: #f24; }
.safe    { color: #42b983; }

點擊文字即可切換文案與顏色:isWarning 為 true 時顯示「紅色警報」並套用紅字,切換後顯示「警報解除」並轉為綠字。這裡的關鍵是 computed 的 isSafe 由 isWarning 反推而來,你不必另外維護狀態,也就不會出現兩者不同步的 bug。

2. 綁定物件參照

把這個物件搬到 Vue 實例的 data 裡,模板上只寫參照名稱。若放在 computed 中,該 computed 屬性必須回傳一個物件:

<div id="classBind">
  <span :class="classObj" v-on:click="toggle">狀態:{{alert}}</span>
</div>

<script>
var app11 = new Vue({
    el: '#classBind',
    data: {
        isWarning: true,
        alertList: ['紅色警報', '警報解除'],
        alert: ''
    },
    computed: {
        isSafe: function () {
            return !this.isWarning;
        },
        classObj: function () {
            return {
                warning: this.isWarning,
                safe: this.isSafe
            };
        }
    },
    methods: {
        toggle: function () {
            this.isWarning = !this.isWarning;
            this.alert = this.isWarning ? this.alertList[0] : this.alertList[1];
        }
    }
});
</script>

這個寫法比物件字面值更適合 class 數量多、或規則需要複雜判斷的情況——模板保持乾淨,邏輯集中在 computed 裡。

3. 綁定陣列

HTML:

<div :class="classArray" @click="removeClass()">去掉 class</div>

JS:

data: {
    classArray: ["big", "red"]
},
methods: {
    removeClass: function () {
        this.classArray.pop();
    }
}

CSS:

.big { font-size: 2rem; }
.red { color: red; }

每點一次就呼叫 removeClass,把陣列最後一項 pop 掉:第一次移除 red,字色由紅轉黑;再一次移除 big,字級變小。陣列寫法的好處是各個 class 彼此獨立、互不干涉,很適合「多個條件各自決定要不要加 class」的場景。此外 Vue 也支援在陣列中混合物件,例如 :class="[baseClass, { active: isActive }]"。

二、綁定 inline style

HTML:

<div id="styleBind">
  <span :style="{ color: theColor, fontSize: theSize + 'px' }" @click="bigger">styleBind</span>
</div>

CSS:這個範例不需要寫任何樣式。

JS:

var app12 = new Vue({
    el: '#styleBind',
    data: {
        theColor: 'red',
        theSize: 14
    },
    methods: {
        bigger: function () {
            this.theSize += 2;
        }
    }
});

每點一次,字級就增加 2px。除了物件字面值,v-bind:style 同樣可以傳入物件參照或陣列。

兩個實務上的提醒

第一,樣式屬性名稱建議使用駝峰式或 kebab-case 皆可,但 JS 物件裡用駝峰最安全(如 fontSize),若要寫 font-size 記得加引號。第二,需要帶單位的值要自己補上字串(theSize + 'px'),Vue 不會幫你猜單位。

總結一句:class 用物件或陣列,style 用物件,把條件判斷交給 Vue 的反應式系統,你就不用再在字串上來回拼接了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved