关于微信小程序:微信小程序自定义tabbar图标切换点击两次才选中解决方法

4次阅读

共计 951 个字符,预计需要花费 3 分钟才能阅读完成。

微信小程序开发过程中应用了自定义 tabBar,运行官网提供的 demo 是没有问题的,然而本人增加了新的 tab-item 后点击会呈现谬误,具体表现为:点击一次 tab 跳到指定的页面,然而 tabBar 的状态还停留在上一个,再次点击能力更新。

问题剖析

Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    list: [{
      pagePath: "/index/index",
      iconPath: "/image/icon_component.png",
      selectedIconPath: "/image/icon_component_HL.png",
      text: "组件"
    }, {
      pagePath: "/index/index2",
      iconPath: "/image/icon_API.png",
      selectedIconPath: "/image/icon_API_HL.png",
      text: "接口"
    }]
  },
  attached() {},
  methods: {switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      this.setData({selected: data.index})
    }
  }
})

在 methods 的 switchTab() 办法中看似在切换 tab 后更新了以后选中的 tab,然而这样是不够的,能够查看对应页面的 show() 中官网还增加了上面的代码:

// 组件页面
show() {
  if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {this.getTabBar().setData({selected: 0})
  }
}

// 接口页面
show() {
  if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {this.getTabBar().setData({selected: 1})
  }
}

咱们本人新增加的页面正是应为短少了这段代码,才会呈现开始提到的问题。在新增的页面增加即可解决,留神你的 selected 值应该是 tabBar 数组中对应的 index。

正文完
 0