项目中底部导航经常使用,为了方便可维护,下次使用直接拿过来使用,封装了一个简单的底部导航栏(自定义TabBar组件)
实现思路:
1.TabBar中显示的内容由外界来定义
使用flex布局平铺TabBar
2.自定义TabBarItem,可以上穿文字图片等(案例中只上穿了文字,图片后面会讲)
1.定义TabBarItem,并定义插槽:文字
2.给插槽外层包裹div,用于设置样式
3.填充插槽,实现底部TabBar效果
效果如图:
在components下建个单独的文件夹tabbar,在tabbar中新建俩文件,分别为TabBar.vue,TabBarItem.vue,在TabBar中引用TabBarItem,相当于引用一个个块
由于TabBarItem中的文字(例:首页,我的...),不确定,用到具名插槽
<slot name="text"></slot>
当点击首页 的时候 ,切换到对应路由,并文字高亮显示,需要父组件(TabBar.vue)传入path,子组件(TabBarItem.vue)来进行接收,根据是否激活来显示对应高亮文字
//判断是否被激活
isActive(){
return this.$route.path.indexOf(this.path) !== -1;
}
//给激活字体添加颜色
isActiveColor(){
return this.isActive ? {color:this.activeColor} :{}
}
完整代码:
TabBar.vue
<template>
<div class="tab_bar">
<!-- activeColor是高亮文字颜色 -->
<tab-bar-item path="/home" activeColor="red">
<div slot="text">首页</div>
</tab-bar-item>
<tab-bar-item path="/my" activeColor="red">
<div slot="text">我的</div>
</tab-bar-item>
</div>
</template>
<script>
import TabBarItem from "../tabbar/TabBarItem";
export default {
components: {
TabBarItem
},
};
</script>
<style lang="less" scoped>
.tab_bar{
position:fixed;
left:0;
bottom:0;
background:#f6f6f6;
height:49px;
display:flex;
width:100%;
}
</style>
TabBarItem.vue
<template>
<div class="tab_bar_item" @click="clickItem">
<!-- 文字 -->
<div :style='isActiveColor'>
<slot name="text"></slot>
</div>
</div>
</template>
<script>
export default {
props:{
path:String, //路径
activeColor:String //被激活的文字颜色
},
computed:{
//判断是否被激活
isActive(){
return this.$route.path.indexOf(this.path) !== -1;
},
//给激活字体添加颜色
isActiveColor(){
return this.isActive ? {color:this.activeColor} :{}
}
},
methods:{
//点击切换对应的路由
clickItem(){
this.$router.push(this.path);
}
}
}
</script>
<style lang="less" scoped>
.tab_bar_item{
flex:1;
text-align: center;
line-height:49px;
}
</style>
补充当底部导航有图片的时候
如图:
这时需要在TabBarItem 在定义俩插槽,一个是高亮图片,一个是未高亮的
<!-- 高亮图片 -->
<div v-if="isActive">
<slot name="img_active" />
</div>
<!-- 未高亮图片 -->
<div v-else>
<slot name="img" />
</div>
<!-- 文字 -->
<div :style='isActiveColor'>
<slot name="text" />
</div>
在TabBar(父组件)中引用
<tab-bar-item path="/home" activeColor="red">
<img solt="img_active" img src="xxxxx" />
<img solt="img" img src="xxxxx" />
<div slot="text">首页</div>
</tab-bar-item>