DEV Community

Maxwell Adapoe
Maxwell Adapoe

Posted on

Creating Tabs with Vue 2 and Tailwind css

So I was building an admin dashboard for hirehex using tailwind and needed to create some Tabs.

To be honest its rather simple to implement but requires some understanding of how components work in vue.js
I will be skipping the vue.js & tailwind project set up. But should you need it, you can check it out here

We will need 2 components for this:
Tab.vue & Tabs.vue

in Tab.vue:

<template>
    <div v-show="isActive">
        <slot></slot>
    </div>
</template>

<script>
    export default {
        name: "Tab",
        props: {
            name: {
                required: true,
                type: [Number, String],
            },
            selected:{
                default: false
            }
        },
        data(){
            return {
                isActive:false
            }
        },
        mounted(){

            this.isActive = this.selected;

        }
    }
</script>



Enter fullscreen mode Exit fullscreen mode

in Tabs.vue:

<template>
    <div>
        <div id="tab-links">
            <ul class="flex space-x-2 ">
                <li v-for="(tab, index) in tabs "
                    :key="index"
                    :class="{'border-b-2':tab.isActive}"
                    class="py-2  border-solid text-center w-40 cursor-pointer"
                    @click="selectTab(tab)">
                    {{tab.name}}
                </li>
            </ul>
            <hr>

        </div>

        <div id="tab-details">
            <slot></slot>
        </div>

    </div>

</template>

<script>
    export default {
        name: "Tabs",
        data() {
            return {
                tabs: []
            }
        },
        created() {
            this.tabs = this.$children;
        },
        mounted() {

            //check if a tab has been selected by default
            let hasTabBeenSelected = this.tabs.findIndex(child=> child.selected ===true)
            //set the default to the first one
            if (hasTabBeenSelected === -1){

                this.tabs[0].isActive=true;
            }

        },
        methods: {
            selectTab(selectedTab) {
                this.tabs.forEach(tab => {
                    tab.isActive = tab.name === selectedTab.name;
                })
            }
        }
    }
</script>

<style scoped>

</style>
Enter fullscreen mode Exit fullscreen mode

With these in place you should have a working tab component.
Feel free to modify this in anyway to meet your use case.
Thanks.

Top comments (1)

Collapse
 
yemikudaisi profile image
Yemi Kudaisi

Good post, usage for learners please ?