Vue筆記(三)class與style綁定 條件渲染指令

class與style綁定

理解
1) 在應用界面中, 某個(些)元素的樣式是變化的
2) class/style 綁定就是專門用來實現動態樣式效果的技術

class 綁定
1) :class='xxx'
2) 表達式是字符串: 'classA'
3) 表達式是對象: {classA:isA, classB: isB}
4) 表達式是數組: ['classA', 'classB']

style 綁定
1) :style="{ color: activeColor, fontSize: fontSize + 'px' }"
2) 其中 activeColor/fontSize 是 data 屬性

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script type="text/javascript" src="../js/vue.js"></script>
  <script type="text/javascript">
    new Vue({
      el: '#demo',
      data: {
        a: 'classA',
        isA: true,
        isB: false,
        color: 'red',
        fontSize: '20px'
      },
      methods: {
        update() {
          this.a = 'classC'
          this.isA = false
          this.isB = true
          this.color = 'blue'
          this.fontSize = '30px'
        }
      }
    })

  </script>
  <style>
    .classA {
      color: red;
    }

    .classB {
      background: blue;
    }

    .classC {
      font-size: 20px;
    }

  </style>
</head>

<body>
  <div id="demo">
    <h2>1. class 綁定: :class='xxx'</h2>
    <p class="classB" :class="a">表達式是字符串: 'classA'</p>
    <p :class="{classA: isA, classB: isB}">表達式是對象: {classA:isA, classB: isB}</p>
    <p :class="['classA', 'classC']"> 表達式是數組: ['classA', 'classB']</p>
    <h2>2. style 綁定</h2>
    <p :style="{color, fontSize}">style="{ color: activeColor, fontSize: fontSize + 'px' }"</p> <button
      @click="update">更新</button>
</body>

</html>

條件渲染指令

1) v-if 與 v-else
2) v-show
比較 v-if 與 v-show
3) 如果需要頻繁切換 v-show 較好
4) 當條件不成立時, v-if 的所有子節點不會解析(項目中使用)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./js/vue.min.js"></script>
    <script type="text/javascript">
        var vm = new Vue({
            el: '#demo',
            data: {
                ok: false
            }
        })
    </script>

</head>

<body>
    <div id="demo">
        <h2 v-if="ok">表白成功</h2>
        <h2 v-else>表白失敗</h2>
        <h2 v-show="ok">求婚成功</h2>
        <h2 v-show="!ok">求婚失敗</h2> <br> <button @click="ok=!ok">切換</button>
    </div>
</body>

</html>

 

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