簡體   English   中英

如何在 Vue.js 中單擊時在兩個選項卡之間切換類

[英]How to toggle classes between two tabs on click in Vue.js

我有spans ,我想讓當我點擊一個選項卡時,點擊的選項卡將其顏色更改為red ,而另一個保持為gray 我試圖通過使用class綁定來實現這一點,但現在沒有任何反應,我該如何修復它以便它開始更改類?

這是我的邏輯:

<template>
    <div class="left-side-tabs">
        <span  :class="[ isClicked ? '.active' : 'normal' ]" @click="toggle()">Shares Distribution</span>
        <span :class="[ isClicked ? '.active' : 'normal' ]" @click="toggle()">Activity Log</span>
         <br>
         <br>
         <br>
    </div>
</template>

<style lang="scss">
@import "../../variables";

.left-side-tabs {
 margin-left: 93px;
  span {
      padding: 10px;
      font-family: Roboto Slab;
      font-style: normal;
      font-weight: bold;
      font-size: 14px;
      line-height: 18px;
      text-transform: uppercase;

      color: $brainstemGrey;
  }

  span:hover {
      cursor: pointer;
  }
}

.active {
    color:red
}

.normal {
   color: $brainstemGrey;
</style>

<script>
export default {
     data() {
    return {
      isClicked: false
    };
  },
  methods: {
      toggle() {
          this.isClicked = !this.isClicked
      }
  }
}
</script>
:class="[isClicked ? 'active' : 'normal' ]"

注意:不要添加. 在類綁定中的類名之前。

上述解決方案將使兩個選項卡具有相同的顏色,因此您應該添加一個名為active的屬性,當您單擊選項卡更新該屬性時,然后根據切換的選項卡索引在您的類中添加一個條件:

 Vue.config.devtools = false; Vue.config.productionTip = false; new Vue({ el: '#app', data() { return { isClicked: false, active:-1 }; }, methods: { toggle(index) { this.active=index } } })
 .left-side-tabs { margin-left: 93px; } .left-side-tabs span { padding: 10px; font-family: Roboto Slab; font-style: normal; font-weight: bold; font-size: 14px; line-height: 18px; text-transform: uppercase; color: $brainstemGrey; } .left-side-tabs span:hover { cursor: pointer; } .active { color: red } .normal { color: gray; }
 <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app" class="container"> <div class="left-side-tabs"> <span :class="{ active===1 ? 'active' : 'normal' }" @click="toggle(1)">Shares Distribution</span> <span :class="{ active===2 ? 'active' : 'normal' }" @click="toggle(2)">Activity Log</span> <br> <br> <br> </div> </div>

這樣做:

 <span  :class="isClicked ? 'active' : 'normal'" @click="toggle()">Shares Distribution</span>

 <span :class="!isClicked ? 'active' : 'normal'" @click="toggle()">Activity Log</span>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM