Vue入門教程07-Class和Style樣式綁定

一、class屬性綁定

1、單樣式使用:

使用 v-bind:class 可以爲元素設置一個樣式:

<template>
  <div id="hello">
    <div v-bind:class="{ class1: use }"></div>
  </div>
</template>
<script>
  export default {
    name: 'hello',
    data () {
      return {
        use:true
      }
    }
  }
</script>
<style>
  .class1 {
    width: 200px;
    height: 200px;
    background: green;
  }
</style>

樣式效果:
在這裏插入圖片描述
上面程序中,use爲true,所以class=class1樣式。

2、疊加樣式使用:

在上面的案例中,我們疊加一個class2樣式,設置被紅色背景,並使其生效:

<template>
  <div id="hello">
    <div v-bind:class="{ class1: use, class2:errorTip }"></div>
  </div>
</template>
<script>
  export default {
    name: 'hello',
    data () {
      return {
        use:true,
        errorTip:true
      }
    }
  }
</script>
<style>
  .class1 {
    width: 200px;
    height: 200px;
    background: green;
  }
  .class2 {
    background: red;
  }
</style>

樣式效果:
在這裏插入圖片描述

3、樣式對象的使用:

上述疊加的樣式我們可以還封裝到一個calssObject對象中,代碼格式更優美:

<template>
  <div id="hello">
    <div v-bind:class="classObject"></div>
  </div>
</template>
<script>
  export default {
    name: 'hello',
    data () {
      return {
        classObject: {
          class1: true,
          class2: true
        }
      }
    }
  }
</script>
<style>
  .class1 {
    width: 200px;
    height: 200px;
    background: green;
  }
  .class2 {
    background: red;
  }
</style>

4、樣式數組語法的使用:

也可以把一個數組傳給 v-bind:class :

  //v-bind:class中使用數組格式來引用:
  <div v-bind:class="[c1,c2]"></div>

  //data返回數組格式的樣式定義:
  data () {
    return {
      c1:'class1',
      c2:'class2'
    }
  }

二、style(內聯樣式)

使用 v-bind:style 直接設置樣式值:

<template>
  <div id="hello">
    <div v-bind:style="{ color: myColor, fontSize: fontSize + 'px' }">內嵌入的式樣使用</div>
  </div>
</template>
<script>
  export default {
    name: 'hello',
    data () {
      return {
        myColor: 'green',
        fontSize: 40
      }
    }
  }
</script>

與上面v-bind:calss一樣,v-bind-style也可以使用對象、數組的格式設置style值,下面程序列舉一個數組模式的實現:

<template>
  <div id="hello">
    <div v-bind:style="[style1,style2]">內嵌入的式樣使用</div>
  </div>
</template>
<script>
  export default {
    name: 'hello',
    data () {
      return {
        style1: {
          color: 'green',
          fontSize: '40px'
        },
        style2: {
          'font-weight': 'bold'
        }
      }
    }
  }
</script>

END.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章