vue3+uniapp自定义tabbar

首先把tabbar中的元素写在一个list中用v-for进行渲染
用一个interface进行定义接口,这样别人在review你的代码就可以清晰知道你的tabbar包含什么元素。
利用typescript特性进行类型定义,可以省去很多麻烦

import { reactive } from "vue"
import { Images } from "src/static/images"
export interface Tabbar {
  iconPath: string,
  selectedIconPath: string,
  text: string,
  url: string
}

export const tabBarList = reactive<Tabbar[]>([
  {
    iconPath: Images.Home,
    selectedIconPath: Images.HomeActive,
    text: '首页',
    url: '/pages/home/home',
  },
  {
    iconPath: Images.Personal,
    selectedIconPath: Images.PersonalActive,
    text: '我的',
    url: '/pages/personal/personal',
  }
])
<template>
  <view class="tabbar-container">
    <view v-for="(item, index) in tabBarList" :key="index" :url="item.url" :class="{ 'active': activeIndex === index }">
      <view class="icon-container" @click="switchTab(index)">
        <view class="icon">
          <image class="icon-image" :src="activeIndex === index ? item.selectedIconPath : item.iconPath" />
        </view>
        <view class="text">{{ item.text }}</view>
      </view>
    </view>
  </view>
</template>

渲染好之后,tabbar有个点击跳转页面,以及点亮图标
点亮图标,这边的currentPath一定注意格式,打印出getCurrentPages()[0].route就会发现它是pages/personal/personal,而不是/pages/personal/personal

//vue
<view class="icon">
          <image class="icon-image" :src="activeIndex === index ? item.selectedIconPath : item.iconPath" />
 </view>
 //js
 const currentPath =  "/" + getCurrentPages()[0].route;
tabBarList.forEach((item, index) => {
  if (item.url === currentPath) {
    store.activeIndex = index;
    uni.switchTab({
      url: item.url,
    })
  }
})

跳转:由于是page页面,因此必须用switchtab方法而不能用nacigatorTo;这边的index及页面序号必须存储在pinia库中,否则界面一刷新它就不变了。

function switchTab(index) {
  if (index === store.activeIndex) {
    return
  }
  store.setActiveIndex(index)
  uni.switchTab({
    url: tabBarList[index].url
  })
}
import { defineStore } from 'pinia'

interface State {
  activeIndex: number;
  sceneId: number;
  isLogin: boolean;
  nickname: string;
  avatar: string
}

export const useTabbarStore = defineStore('store', {
  state: (): State => {
    return { 
      activeIndex: 0,
      isLogin: false,
      sceneId: 1,
      nickname: '立即登录',
      avatar: 'https://bestwellai-aigo.oss-cn-shanghai.aliyuncs.com/icon/personal/personal_avatar.svg' 
    }
  },
  actions: {
    setActiveIndex(index) {
      this.activeIndex = index;
    },
    setUsername(nickname,avatar){
      this.nickname = nickname;
      this.avatar = avatar;
    },
    setSceneId(sceneId) {
      this.sceneId = sceneId;
    }
  },
})

完成效果:自定义的效果就是样式可以自己写,非常方便;以及一个小程序需要三四种形式的tabbar时可以这样操作。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值