![](/img/trans.png)
[英]How to add class to the parent component when the button is clicked in child in vue
[英]How to add default class to first child in vue
我有一個標簽組件:
<template>
<div class="tabs">
<div class="tabs__list">
<div
class="tabs__tab"
:class="{'tabs__tab_active': i === active}"
@click="changeTab(i)"
v-for="(label, i) in Tabs.labels"
:key="i"
>{{label}}</div>
</div>
<div class="tabs__container" ref="container">
<div class="tabs__wrapper" 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>
它有一個子組件 Tab,我正在調用 API 來獲取產品。 每個產品都有變體,每個變體都有名稱。 這就是我的顯示方式:
<div class="tabs-content">
<Tabs v-for="variation in product.attributes.variations">
<Tab :label="variation.name" :active="false">
</Tab>
</Tabs>
</div>
但這里的問題是所有 Tab 組件都有一個“tabs__tab_active”類。 但默認情況下,我只想要第一個孩子。 那么你有什么想法嗎?
您已經將索引從另一個 for 循環中拉出來了。 您應該能夠使用它來添加條件類
<Tabs v-for="(variation, index) in product.attributes.variations">
<Tab :label="variation.name" :active="false" :class="{'tabs__tab_active': index === 0}">
</Tab>
</Tabs>
在你的tabs
組件中試試這個
<div class="tabs__list">
<div
v-for="(label, i) in Tabs.labels"
:key="i"
:class="['tabs__tab', {'tabs__tab_active': i === 0}]" // change added
@click="changeTab(i)"
>{{label}}</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.