自己封装小程序的路由拦截

第一步  我们创建一个拦截的文件  intercept.js

function identityFilter(pageObj) {
    if (pageObj.onShow) {
        let _onShow = pageObj.onShow;
        pageObj.onShow = function () {
            wx.getSetting({
                success: (res) => {
                    // 判断是否登录以及授权了
                    if (res.authSetting['scope.userInfo'] && wx.getStorageSync('userinfo')) {//授权了,可以获取用户信息了
                        //获取页面实例,防止this劫持
                        let currentInstance = getPageInstance();
                        _onShow.call(currentInstance);
                    } else {
                        //重定向到指定的页面
                        wx.redirectTo({
                            url: "/pages/authorize/authorize"
                        });
                    }
                }
            })
        }
    }
    return pageObj;
}

function getPageInstance(){ // 获取去往的页面
    var pages = getCurrentPages(); // getCurrentPages小程序获取页面栈函数
    return  pages[pages.length - 1];
}

exports.identityFilter = identityFilter;

第二步使用路由拦截

// 假设在我的页面需要使用到路由拦截

let intercept = require('../../../utils/intercept.js')

Page(filter.identityFilter({

    /**
     * 页面的初始数据
     */
    data: {
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
  })
)

猜你喜欢

转载自blog.csdn.net/Hgh_1997/article/details/99838078