非TabBar页面怎么更新TabBar上面的小红点或者数字信息
发布于 6 年前 作者 pshi 8137 次浏览 来自 问答
  • 当前 Bug 的表现(可附上截图)
  • 预期表现
  • 复现路径
  • 提供一个最简复现 Demo

在非TabBar页面执行

setTabBarBadge方法不起作用,如何在子页面更新一级页面上的Badge信息?

3 回复

这个就是耗点页面性能,用户手机费点电,但应该不会影响很大吧

结合上面兄弟的分享,我写了目前在用的方法:

app.js

_showBadge: function(num, show) {
    if (show == 0) {
        wx.removeTabBarBadge({ index: 3 });
    } else {
        wx.setTabBarBadge({
            index: 3,
            text: String(num),
        });
    }
},
 
// 微章闪动
_flashingBadge: function(num) {
    var that = this;
    // 隐藏微章 显示微章 * 3
    that._showBadge(num, 0);
    setTimeout(function() {
        that._showBadge(num, 1);
    }, 150);
    setTimeout(function() {
        that._showBadge(num, 0);
    }, 300);
    setTimeout(function() {
        that._showBadge(num, 1);
    }, 400);
    setTimeout(function() {
        that._showBadge(num, 0);
    }, 480);
    setTimeout(function() {
        that._showBadge(num, 1);
    }, 580);
},
 
_clearBadgeTimer: function() {
    var that = this;
    if (that.globalData._setTabBarBadgeTimer) {
        clearInterval(that.globalData._setTabBarBadgeTimer);
        that.globalData._setTabBarBadgeTimer = null;
    }
},
 
_createBadgeTimer: function() {
    var that = this;
    if (that.globalData._setTabBarBadgeTimer) {
        return;
    } else {
        that.globalData._setTabBarBadgeTimer = setInterval(function() {
            that.setMsgBadge(that.globalData.badgeNum);
        }, 300);
    }
},
 
// 设置消息微章
setMsgBadge: function(num) {
    var that = this;
    if (num == 0) {
        that.globalData.badgeNum = 0;
        wx.setStorageSync('badgeNum', 0);
        wx.removeTabBarBadge({
            index: 3,
            success: function() {
                that._clearBadgeTimer();
            },
            fail: function() {
                // 不在tab 页设置会失败 失败就启动定时器 来不断重试,直至成功,这样再回到tab页就不会出现 “Badge未同步” 的问题了
                console.log('wx.removeTabBarBadge fail');
                that._createBadgeTimer();
            },
        });
        return;
    }
 
    if (num > that.globalData.badgeNum) {
        wx.vibrateLong(); // 小震动
        wx.playBackgroundAudio({
            dataUrl: 'https://x.aipin100.cn/static/newMessage.aac',
        });
        that._flashingBadge(num); // 闪动
    }
 
    that.globalData.badgeNum = num;
    wx.setStorageSync('badgeNum', num);
 
    wx.setTabBarBadge({
        index: 3,
        text: String(num),
        success: function() {
            that._clearBadgeTimer();
        },
        fail: function() {
            // 不在tab 页设置会失败 失败就启动定时器 来不断重试,直至成功,这样再回到tab页就不会出现 “Badge未同步” 的问题了
            console.log('wx.setTabBarBadge fail');
            that._createBadgeTimer();
        },
    });
},

我是把 TabBarBadge 的状态存在全局上,每次进入 TabBar 页面时,用 onShow 检测更新

回到顶部