使用uniapp自定义小程序tabBar的时候,会出现点击TabBar,页面切换但是图标没有切换完成的问题,需要二次点击才能正常切换图标.这是由于每个tab页下面的自定义tabBar组件实例是不同的,按照微信官方的解决方案,需要在每个tabBar对应的页面使用getTabBar获取对应页面实例,并调用 setData 更新选中态.

     但是在uniapp中,不能直接使用getTabBar方法,类似教程中使用的是

async onShow() {
	if (typeof this.$mp.page.getTabBar === 'function' && this.$mp.page.getTabBar(){
			console.log(this)
			this.$mp.page.getTabBar().setData({
				selected: 0
			})
		}
},

或

async onShow() {
	if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) {
			console.log(this)
			this.$scope.getTabBar().setData({
				selected: 0
			})
		}
},

这两段代码在我实际工程中,都无法使用,console.log(this)打印结果为unidentified.

后想到,也许是vue3中取消了this,导致unidentified,那如果没有this,该怎么获取getTabBar?

解决方案

import { getCurrentInstance } from "vue";

let { proxy } = getCurrentInstance();

proxy.$scope.getTabBar().setData({ selected: 0, })

就可以正常切换tabBar了

写于2024年1月5日16:32

于Rockway办公室

更多推荐