小程序page里的js比app.js方法先执行时处理方法

新手最近写百度小程序遇到一个问题,写微信小程序时没注意有这个问题,在app.js里定义一个全局变量,又写了一个获取地理位置的方法,然后在index.js里获取这个全局变量的值,结果怎么都获取不到,发现控制台里index.js先执行了 ,之后app.js才执行的

解决办法

app.js

App({
    globalData: {
        url_host:'https://baidu.com',
        thisAdr:''
    },    
    onLaunch(options) {
        // do something when launch
    },
    dili:function(){//获取地理位置
        swan.getLocation({
            type: 'wgs84',
            altitude: true,
            success: res => {
                console.log('getLocation success', res)
                console.log('app---'+res.city)
                this.globalData.thisAdr = res.city
                if (this.callback) { //函数
                    this.callback() //执行函数的回调函数
                }                
            },
            fail: err => {
                console.log('getLocation fail', res)
            },
            complete: () => {
            
            }
        });    
        // console.log(this.globalData.thisAdr)  
    },
    onShow() {
        // do something when show
        this.dili()
    },
    onLaunch(){
    },
    onHide() {
        // do something when hide
    }
});

index.js里调用全局变量

const app = getApp();
var url_host = app.globalData.url_host;
Page({
    data: {
        thisAdr:''
    },
    onLoad: function (options) {// 监听页面加载的生命周期函数
        var that=this
        if (app.globalData.thisAdr) {//判断有没有你要的 没有说明还没返回或者是失败了
            console.log('第一次回调', app.globalData.thisAdr);
            that.setData({
                thisAdr: app.globalData.thisAdr,
            })
        } else { //这个是时候我们在app的config里定义一个函数 给请求成功后调用
            app.callback = () => {
                console.log('再次回调', app.globalData.thisAdr);
                that.setData({
                    thisAdr: app.globalData.thisAdr,
                })
            };
        }
        if(that.data.thisAdr!=''){
            console.log("do something")
        }

         
    }
});

运行结果

你可能感兴趣的:(微信小程序学习笔记)