vue-點擊切換樣式

設置默認第一個樣式爲active

 

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .active {
      color: crimson;
    }
  </style>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for="(item,index) in movies" :class="{active:currentIndex===index}" @click="change(index)">
        <!-- 解釋:active:currentIndex===index -->
        <!-- 判斷當前索引值和currentIndex的值是否相等,得到布爾值true或false,來確定當前的li標籤的樣式爲active -->
        <!-- 要使第一個li標籤的style樣式爲active,那麼設置currentIndex的默認值爲index的第一個值,“0” -->
        <!-- 以此類推,要使第二個li標籤的style樣式爲active,那麼設置currentIndex的默認值爲index的第二個值,“1” -->
        {{item}}
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    const app = new Vue({

      el: '#app',
      data: {
        movies: ['大話西遊', '喜劇之王', '整蠱之王', '長江七號'],
        currentIndex: 0,
      },
      methods: {
        change(index) {
          this.currentIndex = index
          //注意點擊事件要傳入參數index,是當前的li標籤的索引值,讓後函數中讓當前的索引值和currentIndex的值相等,得到布爾值爲true,使當前的樣式爲active
        }
      }
    })
  </script>
</body>

</html>

 

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