class 與 style 是 HTML 元素的屬性,用於設置元素的樣式,咱們能夠用 v-bind 來設置樣式屬性。數組
Vue.js v-bind 在處理 class 和 style 時, 專門加強了它。表達式的結果類型除了字符串以外,還能夠是對象或數組。app
<style> .active { width: 100px; height: 30px; background: #FFFACD; } .active1 { background: #F0F8FF; } .styleWidth{ width: 200px; } .styleHeight{ height: 100px; } .styleColor{ background: #FAF0E6; } .computedStyle{ width: 210px; height: 30px; background: #CAFACD; } .arrayStyle1{ width: 180px; height: 30px; } .arrayStyle2{ background: #FAFCAA; } .arrayStyle3{ background: #DAFAFF; } </style> </head> <body> <div id="app"> <!-- 樣式綁定 --> <div v-bind:class="{active:isActive}">樣式綁定</div> <!-- 樣式覆蓋 --> <div v-bind:class="{active:isActive, active1:isActive1}">樣式覆蓋</div> <!-- 綁定數據對象 --> <div v-bind:class="styleA">綁定數據對象</div> <!-- 綁定返回對象的計算屬性 --> <div v-bind:class="styleB">綁定返回對象的計算屬性</div> <!-- 數組語法 --> <div v-bind:class="[arrayStyle1,arrayStyle2]">數組語法</div> <!-- 使用三元表達式切換屬性 --> <div v-bind:class="[arrayStyle1, isActive?arrayStyle3:'']">使用三元表達式切換屬性</div> <!-- 內聯樣式,注意v-bind是style,不是class了 --> <div v-bind:style="{width: neilian.width + 'px' ,height: neilian.height + 'px' ,background: neilian.bgcolor}">內聯樣式</div> <!-- 內聯直接綁定到樣式對象 --> <div v-bind:style="neilian2">內聯直接綁定到樣式對象</div> <!-- 內聯使用數組將多個樣式對象綁定到一個元素上 --> <div v-bind:style="[neilian2,neilian3]">內聯使用數組將多個樣式對象綁定到一個元素上</div> <!-- 注意:當 v-bind:style 使用須要特定前綴的 CSS 屬性時,如 transform ,Vue.js 會自動偵測並添加相應的前綴。--> </div> <script> new Vue({ el: '#app', data: { neilian:{ width:280, height:25, bgcolor:"#DFFACD" }, neilian2:{ width:"260PX", fontSize:'20px' }, neilian3:{ background: "#CAFACD", }, arrayStyle1:"arrayStyle1", arrayStyle2:"arrayStyle2", arrayStyle3:"arrayStyle3", isActive: true, isActive1: true, styleA:{ styleWidth:true, styleHeight:true, styleColor:true }, msg:{ error:true, isuse:0 }, }, computed:{ styleB:function(){ return{ computedStyle:this.msg.error && this.msg.isuse==0 } } } }) </script> </body>
運行結果this