Vue3实现TabBar底部导航栏灵活组件
时间: 2024-05-11 20:14:26 浏览: 248
vue自定义底部导航栏Tabbar的实现代码
Vue3中可以通过自定义组件实现底部导航栏的灵活组件。以下是一个简单的实现示例:
1. 创建一个TabBar组件,用于展示底部导航栏:
```vue
<template>
<div class="tab-bar">
<slot></slot>
</div>
</template>
<script>
export default {
name: "TabBar",
};
</script>
<style scoped>
.tab-bar {
display: flex;
justify-content: space-around;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
background-color: #fff;
box-shadow: 0 -3px 5px rgba(0, 0, 0, 0.1);
}
</style>
```
2. 在TabBar组件中使用slot插槽,用于接收底部导航栏的子组件。例如:
```vue
<template>
<div class="tab-bar">
<slot></slot>
</div>
</template>
<script>
export default {
name: "TabBar",
};
</script>
<style scoped>
.tab-bar {
display: flex;
justify-content: space-around;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
background-color: #fff;
box-shadow: 0 -3px 5px rgba(0, 0, 0, 0.1);
}
</style>
```
3. 创建底部导航栏子组件,例如TabBarItem。在TabBarItem中可以定义图标、文字和点击事件等属性。例如:
```vue
<template>
<div class="tab-bar-item" :class="{ active: active }" @click="handleClick">
<i :class="icon"></i>
<span>{{ title }}</span>
</div>
</template>
<script>
export default {
name: "TabBarItem",
props: {
icon: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
active: {
type: Boolean,
required: true,
},
},
methods: {
handleClick() {
this.$emit("click");
},
},
};
</script>
<style scoped>
.tab-bar-item {
display: flex;
flex-direction: column;
align-items: center;
font-size: 12px;
color: #666;
}
.tab-bar-item i {
font-size: 20px;
margin-bottom: 2px;
}
.tab-bar-item.active {
color: #007aff;
}
</style>
```
4. 在父组件中使用TabBar和TabBarItem组件。例如:
```vue
<template>
<div>
<router-view />
<TabBar>
<TabBarItem
v-for="(tab, index) in tabs"
:key="index"
:icon="tab.icon"
:title="tab.title"
:active="index === activeIndex"
@click="activeIndex = index"
/>
</TabBar>
</div>
</template>
<script>
import TabBar from "@/components/TabBar.vue";
import TabBarItem from "@/components/TabBarItem.vue";
export default {
name: "App",
components: {
TabBar,
TabBarItem,
},
data() {
return {
tabs: [
{
icon: "icon-home",
title: "首页",
},
{
icon: "icon-category",
title: "分类",
},
{
icon: "icon-cart",
title: "购物车",
},
{
icon: "icon-person",
title: "个人中心",
},
],
activeIndex: 0,
};
},
};
</script>
```
在父组件中使用TabBar和TabBarItem组件,通过循环遍历tabs数组,动态生成底部导航栏子组件TabBarItem,并通过activeIndex属性控制当前激活的子组件。当子组件被点击时,通过click事件向父组件发送消息,触发activeIndex的变化,从而实现底部导航栏的切换。
阅读全文