如下圖 是想實現的效果
對此組件進行分析
tabbaritem.vue代碼塊
<template>
<div class="tab-bar-item">
<div v-if="!isActive" @click="itemClick">
<slot name="item-icon"></slot>
</div>
<slot v-else name="item-icon"></slot>
<div :style="activeStyle">
<slot name="item-text"></slot>
</div>
</div>
</template>
<style scoped>
.tab-bar-item{
flex:1;
text-align: center;
height: 49px;
}
tabbar.vue代碼塊
<template>
<div id="tab-bar">
<slot></slot>
</div>
</template>
<script>
import TabBarItem from "./TabBarItem.vue"
export default {
name:'TabBar',
components:{
TabBarItem
}
}
</script>
<style scoped>
#tab-bar{
display: flex;
flex-direction: row;
background-color: #f6f6f6;
position: fixed;
left: 0;
right: 0;
bottom: 0;
height: 65px;
border: 1px solid #cccccc;
}
</style>
app.vue代碼塊
<template>
<div id="app">
<router-view></router-view>
<tab-bar>
<tab-bar-item path="/home" activeColor="red">
<img src="./assets/img/首页.png" alt="" slot="item-icon"/>
<div slot="item-text">首頁</div>
</tab-bar-item>
<tab-bar-item>
<img src="./assets/img/会员.png" alt="" slot="item-icon"/>
<div slot="item-text">会员</div>
</tab-bar-item>
<tab-bar-item>
<img src="./assets/img/扫一扫.png" alt="" slot="item-icon"/>
<div slot="item-text">扫一扫</div>
</tab-bar-item>
<tab-bar-item>
<img src="./assets/img/设置.png" alt="" slot="item-icon"/>
<div slot="item-text">设置</div>
</tab-bar-item>
</tab-bar>
</div>
</template>
然後需要點擊後圖片和文字都變成紅色由父組件傳過來
//組件部分代碼
<div class="tab-bar-item">
<div v-if="!isActive" @click="itemClick"><slot name="item-icon"></slot></div>
<div v-else><slot name="item-icon-active"></slot></div>
<div :style="activeStyle"><slot name="item-text"></slot></div>
</div>
computed:{
isActive(){
return this.$route.path.indexOf(this.path) !== -1;
},
activeStyle(){
return this.isActive ? {color:this.activeColor}:{}
}
}
//引用組件部分代碼
<tab-bar-item class="tab-bar-item" path="/home" activeColor="#d81e06" >
<img src="~assets/img/首页.png" alt="" slot="item-icon"/>
<img src="~assets/img/首页_active.png" alt="" slot="item-icon-active"/>
<div slot="item-text">首頁</div>
</tab-bar-item>
具體代碼可以到github下載