Vue.js Class 与 Style 绑定
绑定 Class
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>class</title> <style> span{ display:inline-block; } .static{ border:5px solid #000; } .active{ width:100px; height:100px; color:#000; } .text-danger{ background: greenyellow; } </style> </head> <body> <div id="class"> <span class="static" v-bind:class="{ active: activeClass, 'text-danger': errorClass }">1</span> <span v-bind:class="[activeClass, errorClass]">2</span> <span v-bind:class="classObject">3</span> <span v-bind:class="classObject1">4</span> <span v-bind:class="[isActive ? activeClass : ' ', errorClass]">5</span> <!--始终添加 errorClass ,但是只有在 isActive 是 true 时添加 activeClass --> <!--可写为:<div v-bind:class="[isActive : activeClass, errorClass]">5</div>--> <my-component class="static"></my-component> <!--可写为:<my-component v-bind:class="{ static: isActive }"></my-component>--> </div> <script src="js/vue.js"></script> <script> Vue.component('my-component', { template: '<span class="active text-danger">6</span>' }); var vm = new Vue({ el:"#class", data: { activeClass: 'active', errorClass: 'text-danger', classObject: { active: true, 'text-danger':true }, isActive: true, error: null }, computed: { classObject1: function () { return { active: this.isActive && !this.error, 'text-danger': !this.error } } } }) </script> </body> </html>
绑定Style
<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>style</title> </head> <body> <div id="style"> <span v-bind:style="{color: activeColor, fontSize: fontSize + 'px' }">1</span> <span v-bind:style="styleObject">4</span> </div> <script src="js/vue.js"></script> <script> var vm = new Vue({ el:"#style", data: { activeColor: 'red', fontSize:16, styleObject: { color: 'red', fontSize: '16px' } } }) </script> </body> </html>