问题
需要使用 uniapp 在 app 端原生标题栏实现按钮的动态更新,如下:
点击“编辑”和“完成”互相动态切换
解决
在pages.json文件中配置标题栏按钮:
{
"path": "pages/test/test", // 测试展示用
"style": {
"app-plus": {
"titleNView": {
"autoBackButton": false, // 禁用自动显示回退按钮,使用自定义的回退按钮
"buttons": [{
"text": "编辑",
"color": "#007AFF",
"fontSize": "16px",
"float": "right",
"width": "64px"
},
{
"type": "back",
"color": "#007AFF",
"float": "left"
}
]
}
}
}
}
在页面文件中监听自定义标题按钮事件:
<template>
...
</template>
<script>
export default {
onNavigationBarButtonTap(e) {
const index = e.index // 按钮索引
const currentWebview = this.$scope.$getAppWebview() // 只在 app 端生效
var tnObj = currentWebview.getStyle().titleNView // 动态获取 titleNView 配置
const button = tnObj.buttons[index] // 获取按钮配置
if (button.type === 'back') {
uni.navigateBack() // 手动回退
} else {
if (button.text === '编辑') {
tnObj.buttons[index].text = '完成'
// 弹出旧的配置,添加新的配置
var temp = tnObj.buttons.pop()
tnObj.buttons.push({
"text": "全部删除",
"color": "#007AFF",
"fontSize": "16px",
"float": "left",
"width": "98px", // 配置合适的宽度,不然会显示 3 个点
"__cb__": temp.__cb__ // 重点:复制旧配置的标记
})
currentWebview.setStyle({ titleNView: tnObj }) // 更新 titleNView 配置
} else if (button.text === '完成') {
tnObj.buttons[index].text = '编辑'
// 弹出旧的配置,添加新的配置
var temp = tnObj.buttons.pop()
tnObj.buttons.push({
"type": "back", // 变成回退按钮
"color": "#007AFF",
"float": "left",
"__cb__": temp.__cb__ // 重点:复制回旧配置的标记
})
currentWebview.setStyle({ titleNView: tnObj })
} else if (button.text === '全部删除') {
console.log(“写功能逻辑”);
}
}
}
}
</script>
总结
核心思路:
- 在
pages.json中注册一左一右两个自定义按钮 - 在页面的
onNavigationBarButtonTap函数中根据需要动态的更新按钮 - 重点在于每个注册的按钮会分配一个
__cb__参数,携带这个参数,才能触发 2 中的函数 - 如果想要隐藏按钮,直接删除配置会导致显示错误,添加一个文字为空格的按钮即可
一句话总结:通过占位然后动态处理为需要的效果
希望能帮助到大家,如果有其它方案,欢迎评论交流