全网并没有找到一篇可自定义图标的tabbar。
又都是复制的。。。
哎,于是我就来首发第一篇

首先在app.json

"tabBar": {
    "custom": true,
    "list": [
      {
        "text": "天气",
        "pagePath": "pages/index/index"
      },
      {
        "text": "空气质量",
        "pagePath": "pages/quality/index"
      },
      {
        "text": "生活建议",
        "pagePath": "pages/logs/logs"
      }
    ]
  },

在根目录创建custom-tab-bar创建以下文件

  • index.js
  • index.json
  • index.wxss
  • index.wxml

在index.js写上如下参照代码


这里用到了云存储,链接请自行替换

Component({
  data: {
    active:0,
    list:[{
      text:"天气",
      normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/weather_normal.png",
      active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/weather_select.png",
      url:"/pages/index/index"
    },
    {
      text:"空气质量",
      normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/quality_normal.png",
      active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/quality_select.png",
      url:"/pages/quality/index"
    },
    {
      text:"生活建议",
      normal:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/advice_normal.png",
      active:"cloud://airstory-2gfltwcp7e973deb.6169-airstory-2gfltwcp7e973deb-1305977660/advice_select.png",
      url:"/pages/logs/logs"
    },
  ]
  },
  methods: {
    onChange:function(e){
      const i = e.detail;
      wx.switchTab({
        url: this.data.list[i].url,
      })
      this.setData({
        active : i
      })
    },
    init() {
      const page = getCurrentPages().pop();
      this.setData({
        active: this.data.list.findIndex(item => item.url === `/${page.route}`)
      });
     }
  }
})

在index.json引用组件

{
  "component": true,
  "usingComponents": {
    "van-tabbar": "/miniprogram/miniprogram_npm/@vant/weapp/tabbar/index",
    "van-tabbar-item": "/miniprogram/miniprogram_npm/@vant/weapp/tabbar-item/index"
  }
}

在index.wxml,实际上举一反三很简单,只要wx-for循环而已

<van-tabbar active="{{ active }}" active-color="#63bce9" inactive-color="#000" bind:change="onChange">
  <van-tabbar-item wx:for="{{list}}" wx:key="index"> 
    <image slot="icon" src="{{ item.normal }}" mode="aspectFit" style="width: 30px; height: 18px;" />
    <image slot="icon-active" src="{{ item.active }}" mode="aspectFit" style="width: 30px; height: 18px;" />
    {{item.text}}
  </van-tabbar-item>
</van-tabbar>

在使用的页面,例如pages/index/index.js增加生命周期函数,实现高亮

 onShow: function () {
    this.getTabBar().init();
  },

大功告成了!

微信小程序

版权属于:染念
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2021年05月23日 17:09
8
发表评论


180 文章数
673 评论量
4 分类数
184 页面数
已在风雨中度过 7年69天6小时53分
目录
来自 《微信小程序vant框架自定义tabbar实现跳转》
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部