Home > Software design >  How to switch icon when containing class 'active' in Vuejs
How to switch icon when containing class 'active' in Vuejs

Time:09-29

I have a bottom navbar with icons. How can when the router-link has class 'active' it will turn into an active icon? Default icon 1 is active.

  <li>
   <router-link v-if="active" :class="{active}" active-class="active">
      Icon 1 active
    </router-link>
    <router-link v-if="!active" :class="{active}" active-class="active">
      Icon 1
    </router-link>
  </li>
  <li>
   <router-link v-if="active" :class="{active}" active-class="active">
      Icon 2 active
    </router-link>
    <router-link v-if="!active" :class="{active}" active-class="active">
      Icon 2
    </router-link>
  </li>
  <li>
   <router-link v-if="active" :class="{active}" active-class="active">
      Icon 3 active
    </router-link>
    <router-link v-if="!active" :class="{active}" active-class="active">
      Icon 3
    </router-link>
  </li>

CodePudding user response:

The solution:

Binding the HTML class:

  <li>
    <router-link @click="isActive1 = true" :class="{ active: isActive1 }">
      Icon 1
    </router-link>
  </li>
  <li>
    <router-link @click="isActive2 = true" :class="{ active: isActive2 }">
      Icon 2
    </router-link>
  </li>
  <li>
    <router-link @click="isActive3 = true" :class="{ active: isActive3 }">
      Icon 3 Active
    </router-link>
  </li>

Implement isActive variables:

data: {
   isActive1: true, // default icon1 
   isActive2: false,
   isActive3: false,
 }

And implement watchers:

watch: {
  isActive1(val) {
    if(val === true) {
      this.isActive2 = false
      this.isActive3 = false
    }
  },
  isActive2(val) {
    if(val === true) {
      this.isActive1 = false
      this.isActive3 = false
    }
  },
  isActive3(val) {
    if(val === true) {
      this.isActive1 = false
      this.isActive2 = false
    }
  }
}

Documentation: https://vuejs.org/v2/guide/class-and-style.html

  • Related