2

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 Answer 1

11

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Solves my problem and no need to deal with CSS. I didn't know about conditional rendering, thanks! Further reading for people who might visit this in the future: vuejs.org/v2/guide/conditional.html

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.