uni-app uni.setTabBarItem方法修改tabbar跳转路径后 所有页面能跳转 但tabbar在跳转至pages/index/index时不会被选中
uni-app uni.setTabBarItem方法修改tabbar跳转路径后 所有页面能跳转 但tabbar在跳转至pages/index/index时不会被选中
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | Windows 11 | HBuilderX |
示例代码:
export function tabBarNav(key) {
return new Promise((resolve, reject) => {
try {
let tabBarList = getApp().globalData.tabBar[key]
console.log(tabBarList, 'tabBarList')
if (!tabBarList) {
return
}
tabBarList.forEach((v, i) => {
uni.setTabBarItem({
index: i, // tabbar索引,第一个为0
pagePath: v.pagePath, // tabbar页面路径
text: v.text,
iconPath: v.iconPath, // tabbar默认图片路径
selectedIconPath: v.selectedIconPath, // tabbar选中后的图片路径
visible: true,
success: () => resolve(),
fail: (err) => reject(err),
})
})
if (key == 'landlord') {
uni.setTabBarItem({
index: 3,
visible: false,
})
} else {
uni.setTabBarItem({
index: 3,
visible: true,
})
}
} catch (err) {
reject(err)
}
})
}
操作步骤:
export function tabBarNav(key) {
return new Promise((resolve, reject) => {
try {
let tabBarList = getApp().globalData.tabBar[key]
console.log(tabBarList, 'tabBarList')
if (!tabBarList) {
return
}
tabBarList.forEach((v, i) => {
uni.setTabBarItem({
index: i, // tabbar索引,第一个为0
pagePath: v.pagePath, // tabbar页面路径
text: v.text,
iconPath: v.iconPath, // tabbar默认图片路径
selectedIconPath: v.selectedIconPath, // tabbar选中后的图片路径
visible: true,
success: () => resolve(),
fail: (err) => reject(err),
})
})
if (key == 'landlord') {
uni.setTabBarItem({
index: 3,
visible: false,
})
} else {
uni.setTabBarItem({
index: 3,
visible: true,
})
}
} catch (err) {
reject(err)
}
})
}
预期结果:
pages/index/index会被选中
实际结果:
pages/index/index不会被选中
bug描述:
所有动态修改的路径都能正常跳转就是第一个并不会被选中
你好,我这里测试着没有发现这个问题,您可以提供一个可以复现的项目吗?
在uni-app中,uni.setTabBarItem
方法用于动态设置 tabBar 某一项的内容,包括文本、图标等。如果你修改了 tabBar 项的跳转路径,并且希望在跳转到特定页面(如 pages/index/index
)时,对应的 tabBar 项能被自动选中,这通常依赖于框架的内置行为和小部分代码调整。
首先,确保你的 pages.json
配置文件中正确设置了 tabBar 项,例如:
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "首页"
}
},
// 其他页面配置...
],
"tabBar": {
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "static/icon_home.png",
"selectedIconPath": "static/icon_home_active.png"
},
// 其他tab项...
]
}
}
当你使用 uni.setTabBarItem
修改了某个 tabBar 项的 pagePath
后,确保在跳转到新路径时,框架能够识别并选中正确的 tabBar 项。通常,uni-app 会根据当前页面的路径自动选中对应的 tabBar 项,但如果这个行为没有如预期工作,你可以尝试以下方法:
-
在页面
onLoad
或onShow
生命周期中手动设置选中项:假设你修改了 “首页” tab 的跳转路径,并在某个操作中跳转到了新路径,你可以在
pages/index/index
页面的onLoad
或onShow
生命周期函数中添加以下代码,手动设置 tabBar 选中项:onLoad() { // 如果需要,可以在这里添加条件判断 uni.setTabBarStyle({ selectedColor: '#ff0000' // 可选,设置选中项的颜色 }); uni.setTabBarItem({ index: 0, // 首页在 tabBar list 中的索引 selected: true // 设置为选中状态 }); }
-
确保路径一致性:
确保你通过
uni.navigateTo
或其他导航方法跳转的路径与uni.setTabBarItem
中设置的pagePath
完全一致,包括大小写和路径分隔符。 -
框架和依赖更新:
检查你的 uni-app 框架和依赖是否是最新的,有时候框架的 bug 也会导致此类问题。
通过上述方法,你应该能够解决在跳转到 pages/index/index
时 tabBar 项不被选中的问题。如果问题依旧存在,建议检查是否有其他代码或配置影响了 tabBar 的行为。