组件
封装组件为的是以后可以拿来直接用,在使用组件的页面中可以灵活的改变组件的文字、个数、图片、背景、字体颜色以及一些其他效果,可以让别人动态的决定
以封装tabbar组件为例,实现思路
- 先在app.vue页面写所需要的基本结构,然后抽取
- tabber中现实的内容由外界决定(要定义插槽slot,flex布局)
- 自定义tabBarItem,可以传入图片和文字
tabbar
<template>
<div>
<div class="tab_bar">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: "TabBar",
};
</script>
<style scoped>
.tab_bar {
display: flex;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 49px;
background: #f2f2f2;
box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.1);
}
</style>
tabBarItem
<template>
<div class="tab_bar_item" @click="tabBarClick">
<div v-if="!isActive">
<slot name="icon-img"></slot>
</div>
<div v-else>
<slot name="icon-hover-img"></slot>
</div>
<div :style="{ color: isActiveColor }">
<slot name="icon-text"></slot>
</div>
</div>
</template>
<script>
export default {
name: "TabBarItem",
props: {
path: String,
activeColor: {
type: String,
default: "red",
},
},
computed: {
isActive() {
return this.$route.path == this.path;
},
isActiveColor() {
return this.isActive ? this.activeColor : "";
},
},
methods: {
tabBarClick(e) {
if (this.$route.path != this.path) {
// 当前点击的hover为true,其他的为false
// console.log(e)
// console.log(e.target.dataset.index)
this.$router.push(this.path);
this.active = !this.active;
console.log(this.$route);
}
},
},
};
</script>
<style scoped>
.tab_bar_item {
flex: 1;
text-align: center;
}
.tab_bar_item img {
vertical-align: middle;
width: 24px;
height: 24px;
margin-top: 5px;
}
.tab_bar_item div {
font-size: 12px;
}
.active {
color: pink;
}
</style>
MainTabBar
<template>
<div>
<tab-bar>
<tab-bar-item path="/index" activeColor="pink">
<img slot="icon-img" src="~assets/img/tabbar/index.svg" alt="" />
<img
slot="icon-hover-img"
src="~assets/img/tabbar/index_hover.svg"
alt=""
/>
<div slot="icon-text">首页</div>
</tab-bar-item>
<tab-bar-item path="/category" activeColor="pink">
<img slot="icon-img" src="~assets/img/tabbar/cateagry.svg" alt="" />
<img
slot="icon-hover-img"
src="~assets/img/tabbar/cateagry_hover.svg"
alt=""
/>
<div slot="icon-text">分类</div>
</tab-bar-item>
<tab-bar-item path="/cart" activeColor="pink">
<img slot="icon-img" src="~assets/img/tabbar/cart.svg" alt="" />
<img
slot="icon-hover-img"
src="~assets/img/tabbar/cart_hover.svg"
alt=""
/>
<div slot="icon-text">购物车</div>
</tab-bar-item>
<tab-bar-item path="/profile" activeColor="pink">
<img slot="icon-img" src="~assets/img/tabbar/profile.svg" alt="" />
<img
slot="icon-hover-img"
src="~assets/img/tabbar/profile_hover.svg"
alt=""
/>
<div slot="icon-text">我的</div>
</tab-bar-item>
</tab-bar>
</div>
</template>
<script>
import TabBar from "components/common/tabBar/TabBar";
import TabBarItem from "components/common/tabBar/TabBarItem";
export default {
name: "MainTabBar",
components: {
TabBar,
TabBarItem,
},
};
</script>
<style scoped>
</style>