1

I'm attempting to add an active class to an element for tabs navigation using vue.js. The problem is, besides being new to Vue, the navigation items are dynamically created in a for loop as follows:

<c:forEach items="${tabnav.tabs}" var="tab" varStatus="loop">
  <c:if test="${loop.count le tabnav.totalTabs}">
    <li v-bind:class="{active : isActive}" v-on:click="tabSelected = ${loop.count}; isActive = !isActive">${tab.heading}</li>
  </c:if>
</c:forEach>

the JS looks like this:

Vue.component('tabnav', {
    data: function() {
        return {
            tabSelected: 1,
            isActive: false
        };
    }
});

The problem is that this is toggling the class on ALL the items in the navigation rather than the one that was clicked.

Do I need to create a method for handling this?

1 Answer 1

2

Don't use isActive. Check to see if the tabSelected is equal to the current tab in the loop.

v-bind:class="{active : tabSelected === ${loop.count}}"
Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm. Is there anything about this in Vue documentation? Or is this just general knowledge after building Vue skills?
@lscmaro Well, for this in particular, its not really a Vue thing. If you set active based off a global value, then all the tabs will be active when it is set. So you were part way there by storing the currently selected tab in data; you just needed to complete the loop and activate only the tab that is equal to the selected tab, which in your case is identified by loop.count.
That makes sense. Great explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.