1. 程式人生 > >vue最簡單的點選切換active

vue最簡單的點選切換active

很多朋友在做小程式或vue專案選項卡或選擇同類不同項的時候,需要變色的情況,本人提供最簡單的方式,屢試不爽。

timer

我們來完成一個這三個開餐時間,點選那個就對應那個active,並且能獲取對應的資料:

模擬資料

time: [
  {timer: '17'},
  {timer: '18'},
  {timer: '19'}
],

迴圈列表渲染成html,那麼就有了index,也就是所說的下標,沒錯,就是拿下標來玩的,怎麼玩呢?


<li v-for="(item, index) in time"
     key="'time' + index"
     @click="selectTimer(index)"
:class="timeIndex === index ? 'default default-active' : 'default' ">
{{item.title}} </li>

首先重點是 :class=”timeIndex === index ? ” ” : ” “>

然後定義一個timeIndex變數,初始化為0,就是下標為0

// 選擇時間 @click="selectTimer(index)"
selectTimer(index) {
  this.timeIndex = index;
},

上面的函式就是我點選哪個就把他對應的下標賦值,達到指向下標,簡單說,我點了第二個,下標為1,我就把1賦給了我自定義的timeIndex,index 和 timeIndex三元運算子比較自然得出了計算,也就是下面:

 :class="timeIndex === index ? 'default default-active' : 'default ">

最後定義兩個樣式default default-active即好了,用三元執行算符如果點選對應的下標就是真的,反之就假,小程式等等都可以這樣做哦,重要是思維!

比如:(自己喜歡定製樣式)

.default{
  color: #404040;
  background: #f8f8f8;
}

.default-active{
  color: #fff;
  background: #f00;
}