小程序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")
        }

         
    }
});

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章