uniapp使用vue3和ts开发小程序自定义tab栏,实现自定义凸出tabbar效果

要实现自定义的tabbar效果,可以使用自定义tab覆盖主tab来实现,当程序启动或者从后台显示在前台时隐藏自带的tab来实现。自定义一个tab组件,然后在里面实现自定义的逻辑。

组件中所使用的组件api可以看:Tabbar 底部导航栏 | uView 2.0 - 全面兼容 nvue 的 uni-app 生态框架 - uni-app UI 框架

先在components/tabbar/里面实现组件逻辑:

<template>
  <u-tabbar :value="tabIndex" @change="change" :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
    <u-tabbar-item text="首页" icon="home"></u-tabbar-item>
    <view class="tabars" @click="tabMiddle">
      <view class="item">
        <image class="img" src="../../static/images/gongshang.png" mode="widthFix"></image>
      </view>
    </view>
    <u-tabbar-item text="我的" icon="account"></u-tabbar-item>
  </u-tabbar>
</template>

<script setup lang="ts">
import { ref } from 'vue';


const tabIndex = ref(0);

const change = function (index) {
  tabIndex.value = index
  console.log("调用父组件的tab切换", index);
  if (index == 0) {
    uni.switchTab({
      url: '/pages/home/index'
    })
  } else if (index == 1) {
    uni.switchTab({
      url: '/pages/my/index'
    })
  }
};

// 点击中间凸出来的tab
const tabMiddle = function () {
  console.log("点击中间的tab");
}


</script>

<style lang="scss">
.tabars {
  width: 90rpx;
  height: 70rpx;
  display: flex;
  flex-direction: column;
  align-content: center;
  position: relative;
  bottom: 50rpx;
  border-radius: 50%;
  background-color: #fff;
  border-top: 2px solid #dadbde;
  padding: 30rpx;

  .item {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;

    .img {
      width: 80%;
    }
  }
}
</style>

组件里面实现tab切换的api里面使用规范:uni.navigateTo(OBJECT) | uni-app官网

注意看使用switchTab的时候,url的前面要有/,然而pages.json里面的是不需要的。

然后还需要在相应的主页面中引入这个组件:

并且修改一下App.vue文件内容,在启动和显示的时候,隐藏自带的tabbar:

<script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
onLaunch(() => {
  console.log("App Launch");
  uni.hideTabBar()
});
onShow(() => {
  console.log("App Show");
  uni.hideTabBar()
});
onHide(() => {
  console.log("App Hide");
});
</script>
<style lang="scss">
@import "uview-plus/index.scss";
</style>

然后重新打开即可看到效果:

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/134250720
今日推荐