數據綁定一個常見需求是操做元素的 class 列表和它的內聯樣式。由於它們都是屬性 。所以,在 v-bind 用於 class 和 style 時, Vue.js 專門加強了它。表達式的結果類型除了字符串以外,還能夠是對象或數組。web
咱們能夠傳給 v-bind:class 一個對象,以動態地切換 class:數組
<div v-bind:class="{ active: isActive }"></div>
上面的語法表示 classactive 的更新將取決於數據屬性 isActive 是否爲真值 。
在對象中傳入更多屬性用來動態切換多個 class。瀏覽器
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"> </div> data: { isActive: true, hasError: false }
當 isActive 或者 hasError 變化時,class 列表將相應地更新。例如,若是 hasError 的值爲 true , class列表將變爲 "static active text-danger" 。app
你也能夠直接綁定數據裏的一個對象:flex
<div id="app"> <div v-bind:class="classObject">1</div> </div> <script> var vm=new Vue({ el:"#app", data:{ classObject:{ active:true, 'text-danger': true, } </script>
也能夠在這裏綁定返回對象的計算屬性flexbox
<div v-bind:class="classObject"></div> data: { isActive: true, error: null }, computed:{ classObject:function(){ return{ active:true, 'text-danger': true, } } }
咱們能夠把一個數組傳給 v-bind:class,以應用一個 class 列表:code
<div v-bind:class="[activeClass, errorClass]"></div>
data: { activeClass: 'active', errorClass: 'text-danger' }
若是你也想根據條件切換列表中的 class,能夠用三元表達式:component
<div v-bind:class="[cls1,isActive?cls2:'']">1</div>
data:{ isActive:true, cls1:"active", cls2:"text-danger", };
能夠在數組語法中使用對象語法:orm
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
當你在一個自定義組件上用到 class 屬性的時候,這些類將被添加到根元素上面,這個元素上已經存在的類不會被覆蓋。對象
<style> .red{ background: red; } .active{ border:1px solid #ccc; } .blue{ padding: 100px; } </style>
<div id="app"> <alertmsg :class="classObj"></alertmdsg> </div> <script> Vue.component("alertmsg",{ template:`<div class="blue"> <input type="button" value="彈出" v-on:click="tanchu"/> </div> `, methods:{ tanchu:function(){ alert:("123"); } } }); var data={ classObj:{ red:true, active:true } }; var vm=new Vue({ el:"#app", data:data, }); </script>
綁定到一個樣式對象
<div v-bind:style="styleObject"></div>
data:{ styleObj:{ border:"1px solid #ccc", color:"red", width:"200px" },
數組語法能夠將多個樣式對象應用到一個元素上:
<div v-bind:style="[styleObj1,styleObj2]">1</div>
data:{ styleObj1:{ border:"1px solid #ccc", color:"red", width:"200px" }, styleObj2:{ height:"100px", transform:"rotate(20deg)" }, };
當 v-bind:style 使用須要特定前綴的 CSS 屬性時,如 transform,Vue.js 會自動偵測並添加相應的前綴。
從 2.3.0 起你能夠爲 style 綁定中的屬性提供一個包含多個值的數組,經常使用於提供多個帶前綴的值,例如:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
在這個例子中,若是瀏覽器支持不帶瀏覽器前綴的 flexbox,那麼渲染結果會是 display: flex。