1、自定义底部导航组件接收一个tabs
数组作为参数,每个数组项包含icon
和text
字段,用于表示每个底部标签的图标和文本。通过遍历tabs
数组,渲染每个底部标签项的图标和文本。activeIndex
表示当前选中的底部标签的索引。点击底部标签时,调用switchTab
方法切换底部导航,并通过$emit
触发switchTab
事件,将选中的标签索引传递给父组件。
<template> <view class="custom-tab-bar"> <view class="tab-bar-item" v-for="(item, index) in tabs" :key="index" :class="{ active: activeIndex === index }" @click="switchTab(index)"> <!-- 图标 --> <image :src="item.icon" class="tab-bar-icon"></image> <!-- 文字 --> <text>{{ item.text }}</text> </view> </view> </template> <script> export default { props: { tabs: { type: Array, default: () => [] }, activeIndex: { type: Number, default: 0 } }, methods: { switchTab(index) { // 切换底部导航 this.$emit("switchTab", index); } } }; </script> <style scoped> .custom-tab-bar { display: flex; justify-content: space-around; align-items: center; height: 50px; background-color: #fff; } .custom-tab-bar .tab-bar-item { display: flex; flex-direction: column; align-items: center; font-size: 12px; } .custom-tab-bar .tab-bar-item.active { color: #007aff; } .custom-tab-bar .tab-bar-icon { width: 24px; height: 24px; margin-bottom: 4px; } </style>
2、在需要显示自定义底部导航的页面中,引入和使用自定义底部导航组件。例如,在pages
文件夹下的home
页面中,可以添加以下代码:
<template> <view> <!-- 页面内容... --> </view> <!-- 引入自定义底部导航 --> <custom-tab-bar :tabs="tabs" :activeIndex="activeTab" @switchTab="switchTab"></custom-tab-bar> </template> <script> import CustomTabBar from "@/components/CustomTabBar"; export default { components: { CustomTabBar }, data() { return { tabs: [ { icon: "icon-home", text: "首页" }, { icon: "icon-category", text: "分类" }, { icon: "icon-cart", text: "购物车" }, { icon: "icon-mine", text: "我的" } ], activeTab: 0 }; }, methods: { switchTab(index) { // 切换底部导航 this.activeTab = index; // 根据索引进行相应的页面切换或逻辑处理 // ... } } }; </script>