当前位置:   article > 正文

微信小程序 开发 自定义tabbar后,需要选择点击两次才会出现样式选中_微信小程序自定义tabbartabbar图标切换 要点击两次才能有选中状态

微信小程序自定义tabbartabbar图标切换 要点击两次才能有选中状态

微信小程序 开发 自定义tabbar后,需要选择点击两次才会出现样式选中

我先bug复现一下

页面结构

<view class="tab-bar">
  <view class="tab-bar-border"></view>
  <view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
    <image src="{{selected == index ? item.selectedIconPath : item.iconPath}}"></image>
    <!-- <view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view> -->
    <view>{{index}}</view>
  </view>
</view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

页面逻辑

Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#D74446",
    list: [
      {
        "pagePath": "/pages/index/index",
        "text": "首页",
        "iconPath": "/static/icon/tabbar/home.png",
        "selectedIconPath": "/static/icon/tabbar/home-select.png"
      },
      {
        "pagePath": "/pages/credits/index",
        "text": "积分兑换",
        "iconPath": "/static/icon/tabbar/liwu.png",
        "selectedIconPath": "/static/icon/tabbar/liwu-select.png"
      },
      {
        "pagePath": "/pages/orders/index",
        "text": "订单",
        "iconPath": "/static/icon/tabbar/order.png",
        "selectedIconPath": "/static/icon/tabbar/order-select.png"
      },
      {
        "pagePath": "/pages/mine/index",
        "text": "我的",
        "iconPath": "/static/icon/tabbar/mine.png",
        "selectedIconPath": "/static/icon/tabbar/mine-select.png"
      }
    ]
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      this.setData({
        selected: data.index
      })
    }
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

当我们选择了icon 之后按正常的逻辑来说应该会出现高亮显示我们选中的icon
但是实际并没有

bug 复现

观察发现它高亮显示的时候是上一次我们点击的时候或者是我们双击时才出现高亮
我们对该组件的数据进行观察时发现,这个数据已经更新了在这里插入图片描述
可是为什么还是需要双击
这时候我又对组件的数据,在调试工具中打开查看
在这里插入图片描述
这个时候发现数据并没有被更新为1
在这里插入图片描述
如果我们亲自修改数据时发现它可以正常显示的。

分析完毕

通过以上分析发现导致这个错误的原因是因为我们在做this.setData()时并没有真正修改到data中的selected

解决方案

尝试了还半天没有效果,最后在官网发现了这句话
在这里插入图片描述
按照官网的说明来进行修改
在每个tabbar 所要跳转的页面的onShow 钩子函数中加上这个代码

onShow(){
      if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3 // 控制哪一项是选中状态
      })
    }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

后发现问题确实解决了。
但是出现了一个新问题,你每次加载这个页面的时候,这个图标会闪

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/89969
推荐阅读