数据绑定一个常见需求是操做元素的 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。