Tabbed navigation in Vue.Js

6.8k views Asked by At

I'm trying to create a basic tabbed navigation system with Vue. I'm capturing user's navigation choice and calling a function which changes a certain data. That data is eventually going to determine which tab should be active. So far I have this:

HTML

<div id="app">
    <div id="nav">
        <a href='#' class="tab" v-on:click="makeActive('homeActive')">Home</a>
        <a href='#' class="tab" v-on:click="makeActive('infoActive')">Info</a>
    </div>
    <div class="content">
        <div class="boxes" id="home" v-bind:class="choice">
        </div>
        <div class="boxes" id="info" v-bind:class="choice">
        </div>
    </div>
</div>

Vue

new Vue({
    el: '#app',
    data: {
        choice: 'homeActive' // Home is chosen by default
    },
    methods: {
        makeActive: function(val) {
            this.choice = val;
        }
    }
});

At the moment, if the user clicks on Home link, both home and info divs get homeActive class, this is because I couldn't manage to return two statements with my methods with this basic logic:

enable tab1 & disable tab2 || enable tab 2 & disable tab1

I'm trying different approaches but I can affect only a single state with called methods due to binding my content to a single class.

Any suggestions on how I can get this working with Vue?

1

There are 1 answers

1
jessegavin On BEST ANSWER

The way I generally solve this is by adding another function isActiveTab like so...

new Vue({
    el: '#app',
    data: {
        choice: 'homeActive' // Home is chosen by default
    },
    methods: {
        makeActive: function(val) {
            this.choice = val;
        },
        isActiveTab: function(val) {
          return this.choice === val;
        }
    }
});

Then in your view...

<div id="app">
    <div id="nav">
        <a href='#' class="tab" v-on:click="makeActive('homeActive')">Home</a>
        <a href='#' class="tab" v-on:click="makeActive('infoActive')">Info</a>
    </div>
    <div class="content">
        <div class="boxes" id="home" v-show="isActiveTab('homeActive')">
        </div>
        <div class="boxes" id="info" v-show="isActiveTab('infoActive')">
        </div>
    </div>
</div>