Home > Enterprise >  How to add default class to first child in vue
How to add default class to first child in vue

Time:11-10

I have a Tabs component:

<template>
    <div >
        <div >
            <div
                
                :
                @click="changeTab(i)"
                v-for="(label, i) in Tabs.labels"
                :key="i"
            >{{label}}</div>
        </div>
        <div  ref="container">
            <div  ref="wrapper">
                <slot />
            </div>
        </div>
    </div>
</template>
<script>
export default {
    computed: {
        active() {
            return this.Tabs.active
        }
    },
    data() {
        return {
            Tabs: {
                labels: [],
                items: [],
                active: 0
            }
        }
    },
    methods: {
        setHeight() {
            const el = this.Tabs.items[this.active]
            const height = el.scrollHeight
            this.$refs.container.style.height = height   'px'
        },
        scrollWrapper() {
            const {wrapper} = this.$refs
            const offset = 100 * this.active
            wrapper.style.transform = `translate3d(-${offset}%, 0, 0)`
        },
        changeTab(i) {
            this.Tabs.active = i
            this.setHeight()
            this.scrollWrapper()
        }
    },
    provide() {
        return {
            Tabs: this.Tabs
        }
    },
    mounted() {
        this.setHeight()
        this.scrollWrapper()
        this.debounce = _.debounce(this.setHeight, 50)
        window.addEventListener('resize', this.debounce)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.debounce)
    }
}
</script>

And it has a child component Tab and I am making an API call to get the products. Each product has variations and each variations have name. This is how I am displaying:

<div >
                            <Tabs v-for="variation in product.attributes.variations">
                                <Tab :label="variation.name" :active="false">
                                </Tab>
                            </Tabs>
                        </div>

But here the problem is all Tab component has a class of 'tabs__tab_active'. But as a default, I only want first child. So do you have any idea?

enter image description here

CodePudding user response:

You are already pulling the index out of the other for loop. You should be able to use that to add a conditional class

<Tabs v-for="(variation, index) in product.attributes.variations">
  <Tab :label="variation.name" :active="false" :>
  </Tab>
</Tabs>

CodePudding user response:

Try this in your tabs component

<div >
            <div
                v-for="(label, i) in Tabs.labels"
                :key="i"
                : // change added
                @click="changeTab(i)"
            >{{label}}</div>
</div>
  • Related