项目演示结果:?
项目结构:
?
项目代码
1.index.vue
<template>
<div id="app">
<tabs :currentIndex="currentIndex" @changTab="changeTabHandler">
<tab tabName="tab1" index="1">
<div>内容1</div>
</tab>
<tab tabName="tab2" index="2">
<div>内容2</div>
</tab>
<tab tabName="tab3" index="3">
<h3>内容3</h3>
</tab>
</tabs>
</div>
</template>
<script>
import tabs from '@/components/tabs/tabs.vue';
import tab from '@/components/tabs/tab.vue';
export default {
data(){
return{
currentIndex:"1"
}
},
components: {
tabs,
tab,
},
methods:{
changeTabHandler(index){
this.currentIndex = index;
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
?2.tabs.vue
<script>
import Content from "./content.vue"
export default {
name:"Tabs",
data(){
return{
panes:[]
}
},
props:{
currentIndex:{
type:[String,Number],
default:"1"
}
},
methods:{
onChangeIndex(index){
this.$emit("changTab",index);
}
},
render(){
return(
<div>
<ul class="tabs-header">
{ this.$slots.default }
</ul>
<Content panes={ this.panes }/>
</div>
)
}
}
</script>
<style scoped>
.tabs-header {
display: flex;
list-style: none;
margin: 0;
padding: 0;
border-bottom: 2px solid #ededed;
}
</style>
3.tab.vue
<script>
export default {
name:"Tab",
props:{
index:{
type:[String,Number],
default:"1"
},
tabName:{
type:String,
default:"tab"
}
},
mounted() {
this.$parent.panes.push(this);
},
computed:{
active(){
return this.$parent.currentIndex == this.index
}
},
methods:{
changeIndexHandler(){
// 把数据传递给父元素
// this.$emit("onChangeIndex",this.index);
this.$parent.onChangeIndex(this.index);
}
},
render(){
let className = {
tab:"tab",
active:this.active
}
return(
<li onClick={ this.changeIndexHandler.bind(this) } class={ className }>{ this.tabName }</li>
)
}
}
</script>
<style scoped>
.tab {
flex:1;
list-style: none;
line-height: 40px;
margin-right: 30px;
position: relative;
text-align:center;
}
.tab.active {
border-bottom: 2px solid blue;
}
</style>
4.content.vue
<script>
export default {
name: "Content",
props: {
panes: {
type: Array,
default: function() {
return [];
}
}
},
render() {
return (
<div>
{
this.panes.map((element,index) => {
return element.active ? element.$slots.default : "" ;
})
}
</div>
);
}
};
</script>
<style scoped>
</style>
|