Vue语法学习第四课(2)——class与style的绑定

  之前学到的指令 v-bind 在用于绑定class和style时,表达式结果可以是字符串、数组、对象。

一、绑定HTMLClass

  ① 对象语法

  <div class="static" v-bind:class="{active : isActive, 'text-danger' : hasEorro}"></div>
    data:{
      isActive : true ,
      hasEorro : false 
    }

   渲染结果为:

 <div class="static active " ></div>

   注:当v-bind:class的表达式的值为 false,0,""(空字符串),null,undefined,NaN(Not a number) 时在JavaScript中为布尔值的假,即falsy,此时不会渲染

   上述的例子可以写成:

  <div class="static" v-bind:class="classObject"></div>
  data : {
    classObject : {
      active : true,
      'text-danger' : false
    }  
  }

  还可以绑定一个返回对象的计算属性(常用且强大):

    <style>
    .redborder{
        border : 1px solid red
    }
    .yellowbackground{
        background-color : yellow
    }
    </style>
    <div id="app0">
        <input type="text" v-model="myname"/>
        <p v-bind:class="pclass">
            my name is : {{myname}}
        </p>
    </div>    
    <script>
        var vm = new Vue({
            el:"#app0",
            data:{
                myname : "zxq",
                pclass : {
                    yellowbackground: 1,
                    redborder : true
                }
            }
        });
    </script>

② 数组语法

  同理,也可以用数组一次性绑定多个class

    <div v-bind:class="[activeClass,errorClass]"></div>
    data:{
       activeClass : 'active',
       errorClass : 'text-danger'
    }

③ 用于组件

  当在一个自定义组件上绑定class时,这些class将被绑定到组件的根节点上,且原有的class不会被覆盖

    Vue.component('my-component',{
     template : "<div class='foo bar'>hi</div>"
  })

  <my-component class='Active text-danger'></my-component>

      将会被渲染成

    <div class="active text-danger foo bar">hi</div>

   同理也可以使用v-bind绑定class

二、绑定style

① 同class,绑定style时也支持对象语法和数组语法

② 当使用v-bind:style时,需要添加浏览器引擎前缀的CSS属性,如transform,Vue.js会自动侦测补全

③ 从2.3.0开始,可以为style绑定中给的属性提供一个包含多个值的数组,常用于提供多个带前缀的值。

    <div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

  这样写只会渲染数组中最后一个被浏览器支持的值,如上中,如果浏览器支持不带前缀的flexbox,那么就只会渲染display:flex。