小程序学习(四):项目实战之开发TabBar

208 阅读1分钟

一、简介

在上一章 juejin.cn/post/726757… 中已经开发了一个浮动的静态TabBar,本章节我们就进行完善,最终效果如下

1692245617900.png

1692245617904.png

二、完善TabBar

1. 样式完善

  1. 新增触底传统TabBar样式
.tabbar-body_bottom {
  padding: 20rpx 0;
  position: fixed;
  bottom: 0;
  width: 100%;
  background: #fff;
}
  1. 替换最外层Class样式
<view class="tabbar-body_bottom flex flex-col">
  1. 就得到这样的传统TabBar了 image.png

2. 样式配置

新增props变量 改为可配式组件

轻松简单三步即可实现

defineProps({
  float: {
    type: Boolean,
    value: false
  }
});
<view class="flex flex-col" :class="float ? 'tabBar-body' : 'tabBar-body-bottom'">
<TabBar float/>

5. 动态TabBar数据

  1. 接收props变量
const props = defineProps({
  float: {
    type: Boolean,
    value: false
  },
  tabBarList: {
    type: Array,
    default: []
  }
});
  1. 分析组件看需要传入的数据
  • tab 名
  • tab 图标
  • tab 索引
  • tab 选中触发方法 主要针对中间一个扫一扫 点击之后不跳转只执行方法
  • tab 是否浮动 针对扫一扫标签浮动 其他不浮动的情况
interface TabItemType {
  index: number
  title: string
  icon: string
  float?: boolean
  onClick?: Function
}
  1. 编写Mock数据

icon 我们可以直接使用Uni自带的 uniapp.dcloud.net.cn/component/u…

放到父组件中 通过父组件传参到TabBar组件中

const tabBarList = [
  {
    index: 1,
    title: "首页",
    icon: "home",
    onClick: () => console.log("跳转到首页")
  },
  {
    index: 2,
    title: "扫一扫",
    icon: "scan",
    float: true,
    onClick: () => console.log("打开相机")
  },
  {
    index: 3,
    title: "我的",
    icon: "person",
    onClick: () => console.log("跳转到我的")
  }
]
<TabBar float :tab-bar-list="tabBarList"/>
  1. 使用数据渲染静态模板
<view class="flex">
  <view class="tqb-tabBar-item">
    <view class="tabBar-item-body" v-for="tabItem in tabBarList" :key="tabItem.index"
          :class="{float: tabItem?.float}">
      <view class="tabBar-item-icon">
        <uni-icons :type="tabItem.icon" :size="tabItem?.float?48:28"/>
      </view>
      <view class="tab-bar-text">{{ tabItem.title }}</view>
    </view>
  </view>
</view>
  1. 更新选中样式
<view class="tabBar-item-body" v-for="tabItem in tabBarList" :key="tabItem.index"
      :class="{float: tabItem?.float, active: modelValue === tabItem.index}"
      @click="onClick(tabItem)">
      ......
  1. 选中更新样式方法
const modelValue = ref<number>(1)
    
function onClick(tabItem: TabItemType) {
  if (modelValue.value == tabItem.index) return;
  tabItem?.onClick()
  if (tabItem.index === 2) return
  modelValue.value = tabItem.index
}

三、结语

代码已上传到:gitee.com/zegege/t-un…

可以查看专栏:juejin.cn/column/7266… 一起学习