Vue 樣式綁定的幾種方式


樣式動態綁定

  • Vue.js v-bind 在處理 class 和 style 時, 專門增強了它.表達式的結果類型除了字符串之外,還可以是對象或數組

script 部分如下

 data: {
      isActive: true,
      isActive_1: false,
      hasError: true,
      isCenter: true,
      error: null,
      activeClass: 'active',
      centerClass: 'center',
      class_exp: {
       'active': true,
       'center': false,
       'orange': true
       }
      },
computed: {
      computed_obj: function() {
            return {
                  orange: this.isActive && !this.error,
                  center: this.isCenter,
                  'text-danger': this.error && this.error.type === 'fatal',
                  }
       }
}
.active {
    width: 300px;
    height: 100px;
    background: green;
}

.text-danger {
    background: red;
}

.center {
    text-align: center;
}

.orange{
    background: orange;
}
<!-- 1: 動態添加class -->
<div :class="{active: isActive, center:isCenter}">:class="{active: isActive,center:isCenter}}"</div>
<!-- 如果 isActive 和 isCenter 為 true -->
<div class="active center">class="active center"</div>
<!-- 2: 直接綁定數據里的一個對象 -->
<!-- 對象就是一個樣式的表達式: class="{class1: true, class2: true, class3: false}"-->

 <div :class="class_exp">
      class_exp: {
            'active': true,
            'center': false,
            'orange': true
      }
</div>
<!-- 3: 在這里綁定返回對象的計算屬性.這是一個常用且強大的模式-->
<!-- 對象就是一個樣式的表達式: class="{class1: true, class2: true, class3: false}"-->

 <div :class="computed_obj">
      computed:{
            computed_obj: function(){
                  return {
                        orange: this.isActive && !this.error,
                        center: this.isCenter,
                        'text-danger': this.error && this.error.type === 'fatal',
                    }
            }
      }
</div>
<!-- 4: 把一個數組傳給 :class-->
 <!-- 每一個數組元素指向一個 css class -->

<div :class="[activeClass,centerClass]">Use array</div>
<!-- 5: 使用三元表達式來切換列表中的 class-->
<!-- centerClass 始終存在. activeClass根據條件 -->

div :class="[centerClass, isActive_1? activeClass:'']"></div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM