AvocadoFriedEgg
AvocadoFriedEgg

Reputation: 21

Active class not reactive on the first load using vue.js

So I am building a tab component and using :class to bind the active class like this.

<nav class="tabs__header" >
  <ul>
    <li>
      <a
        ref="tabItems"
        v-for="(tabItem, idx) in tabs"
        :key="tabItem.idx"
        :class="{ 'b-active': idx === selectedIndex }"
        @click="changeTab(idx)">
        <span v-if="icon"> {{ tabIcon }} </span>
        {{ tabItem.name }}
      </a>
    </li>
  </ul>
</nav>

The selectedIndex is set with tabIndex value when mounted() for the first time and updated based on the 'idx' selected afterward. I have no problem with the b-active class if we click the tab manually, but it not bind the tabIndex value assigned in mounted().

This is the script I use to directly add value '0' for testing and still not get anything.

  props: {
   tabIndex: {
     type: String,
     default: '0'
  },

  mounted() { this.selectedIndex = this.tabIndex }

can anyone help me? because it seems very simple and I couldn't figure it out for 2 days

Upvotes: 1

Views: 1079

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

At initial render idx seems to be undefined.

Replace this:

:key="tabItem.idx"

With this:

:key="idx"

This now should work fine.

Alternatively, you may use v-for like:

v-for="tabItem in tabs"

Now, using tabItem.idx works just fine as you do in others like tabItem.name.

So, here's your code updated:

<nav class="tabs__header" >
  <ul>
    <li>
      <a
        ref="tabItems"
        v-for="tabItem in tabs"
        :key="tabItem.idx"
        :class="{ 'b-active': tabItem.idx == selectedIndex }"
        @click="changeTab(idx)">
        <span v-if="icon"> {{ tabItem.icon }} </span>
        {{ tabItem.name }}
      </a>
    </li>
  </ul>
</nav>

Upvotes: 1

AvocadoFriedEgg
AvocadoFriedEgg

Reputation: 21

The problem solved and it turns out to be the data type problem, apparently tabIndex is a String and selectedIndex is a Number. I changed:

:class="{ 'b-active': idx === selectedIndex }"

to:

:class="{ 'b-active': idx == selectedIndex }"

and it worked!

Upvotes: 1

Related Questions