新建的uni-app项目会有个app.vue文件,在此文件下 onLaunch应用生命周期封装一个方法(把全局变量定义一下):

注意:onLaunch应用生命周期只会触发一次

app.vue:

<script>
    export default {
        //全局变量
        globalData: {
            //用于判断用户是否登录(默认为否)
            userLogin: false,
        },
        onLaunch: function() {
            console.log('App Launch')
            //是否判断登录
            wx.checkSession({
                success: () => {
                    //没用到token可以直接忽略以下步骤:
                    console.log('登录未过期');
                    const user_token = uni.getStorageSync('user_token');
                    if (user_token) {
                        this.globalData.userLogin = true;
                    } else {
                        //解决token消失但登录未过期问题
                        this.globalData.userLogin = false;
                        //没登录就异步删除验证token
                        uni.removeStorage({
                            key: 'user_token',
                            success: function(res) {
                                console.log('user_token移除成功');
                            }
                        });
                    }
                    //没用到token走这个步骤:
                    //this.globalData.userLogin = false;
                },
                fail: () => {
                    console.log('登录已过期');
                    this.globalData.userLogin = false;
                    //没用到token可以直接忽略以下步骤:
                    //没登录就异步删除验证token
                    uni.removeStorage({
                        key: 'user_token',
                        success: function(res) {
                            console.log('user_token移除成功');
                        }
                    });
                }
            })
        },
        onShow: function() {
            console.log('App Show')
        },
        onHide: function() {
            console.log('App Hide')
        }
    }
</script>

<style>
    /*每个页面公共css */
    @import url("@/common/css/global.css");
    @import url("@/common/css/index.less");
</style>

封装完成之后在pages页面里(自定义组件或页面里)获取全局变量即可:

pages页面里获取:

onLoad() {
    //获取全局变量 赋值后处理业务逻辑
    let app = getApp();
    this.userLoginFlag = app.globalData.userLogin;
    console.log(app.globalData.userLogin);
}

自定义组件或者页面(组件生命周期): 

created() {
    //拿到全局变量
    let app = getApp();
    console.log(app.globalData.userLogin);
    this.userLoginFlag = app.globalData.userLogin;
}
THE END

本站部分文章搜集整理于互联网或者网友提供,如有侵权请联系站长

如若转载,请注明出处:https://www.htmlbk.com/web/973.html

温馨提示:该文档最后一次修改时间为2022-07-09 21:52:08,请注意相关的内容是否还可用!