element ui 中Tabs:
https://element.eleme.io/#/zh-CN/component/tabs
它的例子很簡單换团,tabs中都是文字,但是一般情況下宫蛆,我們的tabs中間都是組件艘包,那么該如何寫呢的猛?很容易想到,用v-for
就行了
<template>
<el-tabs v-model="activeName" type="border-card">
<el-tab-pane :label="title.label" :name="title.name" :key="title.name" v-for="title in header">
<childcomponent></childcomponent>
</el-tab-pane>
</el-tabs>
</template>
<script>
import childcomponent from childcomponent
export default {
name: "tabs",
data() {
return {
activeName: 'all',
header: [
{label: 'A', name: 'a'},
{label: 'B', name: 'b'},
{label: 'C', name: 'c'},
{label: 'D', name: 'd'}
]
}
},
compontents:{
childcomponent
}
}
</script>
<style scoped>
</style>
這樣想虎,貌似沒有問題卦尊,但是接著往下開發(fā)的時候,我們會發(fā)現舌厨,每次換tab的時候岂却,子組件的mounted()
函數都會被觸發(fā)4次。這是因為每次我們按tab的時候裙椭,都有4個子組件被渲染躏哩。所以我們要用v-if來選擇渲染的組件。
<template>
<el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
<el-tab-pane :label="title.label" :name="title.name" :key="title.name" v-for="title in header">
<childcomponent v-if="title.content"></childcomponent>
</el-tab-pane>
</el-tabs>
</template>
<script>
import childcomponent from
childcomponent
export default {
name: "tabs",
data() {
return {
activeName: 'a',
header: [
{label: 'A', name: 'a', content: true},
{label: 'B', name: 'b', content: false},
{label: 'C', name: 'c', content: false},
{label: 'D', name: 'd', content: false}
]
}
},
compontents: {
childcomponent
},
menthods: {
handleClick(tab) {
if (tab.name === "a") {
this.header[0]['content'] = true
this.header[1]['content'] = false
this.header[2]['content'] = false
this.header[3]['content'] = false
} else if (tab.name === "b") {
this.header[0]['content'] = false
this.header[1]['content'] = true
this.header[2]['content'] = false
this.header[3]['content'] = false
} else if (tab.name === "c") {
this.header[0]['content'] = false
this.header[1]['content'] = false
this.header[2]['content'] = true
this.header[3]['content'] = false
} else if (tab.name === "d") {
this.header[0]['content'] = false
this.header[1]['content'] = false
this.header[2]['content'] = false
this.header[3]['content'] = true
}
}
}
}
</script>
<style scoped>
</style>
這樣就可以每次只觸發(fā)一個組件了揉燃。如果有兩層扫尺,三層tabs,只需要在下一層的<el-tabs>
上添加上一層的v-if
<el-tabs v-model="activeName2" type="border-card" @tab-click="handleClick2" v-if="title.content">