普通选项卡组件
<div id="app">
<b-tab :list="carList"></b-tab>
</div>
<script>
Vue.component('b-tab', {
props:["list"],
template:`
<div class="tabs">
<ul class="flex tab">
<li @click="activeIndex=i" :class="{active:activeIndex===i}" v-for="(item,i) in list">{{item.title}}</li>
</ul>
<ul>
<li v-show="activeIndex===i" v-for="(item,i) in list">{{item.content}}</li>
</ul>
</div>
`,
data() {
return {
//高亮索引
activeIndex:0
}
},
})
new Vue({
el:"#app",
data() {
return {
carList:[{
title:'大众',
content:'大众大众的'
},{
title:'奥迪',
content:'奥迪迪奥的'
},{
title:'宝马',
content:'宝马马云的'
},{
title:'奔驰',
content:'奔驰驰名商标的'
}]
}
},
})
</script>
父子组件选项卡案例
<div id="app">
<b-tab>
<b-tab-item title="大众">
<input type="text" value="大众汽车质量非常好">
<input type="text" value="大众汽车质量非常好">
</b-tab-item>
<b-tab-item title="奔驰">
<button>奔驰汽车速度非常快</button>
<button>奔驰汽车速度非常快</button>
</b-tab-item>
<b-tab-item title="保时捷">
<textarea>保时捷汽车外观非常美</textarea>
<textarea>保时捷汽车外观非常美</textarea>
</b-tab-item>
</b-tab>
</div>
<script>
//选项卡组件的子组件
Vue.component('b-tab-item', {
props:["title"],
template:`
<li v-show="show">
<slot></slot>
</li>
`,mounted() {
// 通过$parent给父组件的titleList数组添加元素
this.$parent.titleList.push(this.title)
},
data() {
return {
show:false,
}
}
})
//选项卡组件
Vue.component('b-tab', {
template:`
<div class="tabs">
<ul class="flex tab">
<li @click="activeIndex=i" :class="{active:activeIndex===i}" v-for="(item,i) in titleList">{{item}}</li>
</ul>
<ul>
<slot></slot>
</ul>
</div>
`,
data() {
return {
//选项卡的标题数组
titleList:[],
//高亮索引
activeIndex:0
}
},
watch:{
//监听器方法的第一个参数是新值,第二个参数是旧值
activeIndex(nval,oval){
//切换显示的内容
this.$children[nval].show = true
this.$children[oval].show = false
}
},
mounted() {
//加载完成时,显示默认高亮对应的内容
this.$children[this.activeIndex].show = true
},
})
new Vue({
el:"#app",
data() {
return {
}
},
})
</script>