app.js中的App函數用來注冊一個小程序或設置全局變量。
App函數:
語法:App(Object)
參數: Object json對象
說明: App函數必須在app.js中調用,必須調用且只能調用
1 App({ 2 3 /** 4 * onLaunch(Object) 5 * 說明: 小程序初始化完成時觸發,全局只觸發一次。 6 * 參數: Object, 可從參數Object獲取以下值: 7 * Object.path [String] 打開小程序的路徑 8 * Object.query [String] 打開小程序的query 9 * Object.scene [Number] 打開小程序的場景值(值對應的場景:https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/scene.html) 10 * Object.shareTicket [String] 轉發分享信息,詳見https://developers.weixin.qq.com/miniprogram/dev/api/share.html#wxgetshareinfoobject 11 * Object.referrerInfo [Object] 當場景為由從另一個小程序或公眾號或App打開時,返回此字段 12 * Object.referrerInfo.appId [String] 來源小程序或公眾號或App的 appId 13 * Object.referrerInfo.extraData [Object] 來源小程序傳過來的數據,scene=1037或1038時支持 14 * 15 * 注意: referrerInfo、referrerInfo.appId、referrerInfo.extraData與scene場景值有關聯 16 **/ 17 onLaunch : function(Object){ 18 }, 19 20 21 /** 22 * onShow(Object) 23 * 說明: 小程序啟動,或從后台進入前台顯示時觸發。 24 * 參數: Object, 與onLaunch參數相同 25 **/ 26 onShow : function(Object){ 27 }, 28 29 30 /** 31 * onHide() 32 * 說明: 小程序從前台進入后台時觸發。 33 **/ 34 onHide : function(){ 35 }, 36 37 38 /** 39 * onError(error) 40 * 說明: 小程序發生腳本錯誤,或者 api 調用失敗時觸發。 41 * 參數: error [String] 錯誤信息,包含堆棧 42 **/ 43 onError : function(error){ 44 }, 45 46 47 /** 48 * onPageNotFound(Object) 49 * 說明: 小程序要打開的頁面不存在時觸發。 50 * 參數: Object, 可從參數Object獲取以下值: 51 * Object.path [String] 不存在頁面的路徑 52 * Object.query [Object] 打開不存在頁面的 query 53 * Object.isEntryPage [Boolean] 是否本次啟動的首個頁面(例如從分享等入口進來,首個頁面是開發者配置的分享頁面) 54 * 55 * 注意: 56 * 1) 開發者可以在 onPageNotFound 回調中進行重定向處理(wx.redirectTo...),但必須在回調中同步處理,異步處理(例如 setTimeout 異步執行)無效。 57 * 2) 如果開發者沒有添加 onPageNotFound 監聽,當跳轉頁面不存在時,將推入微信客戶端原生的頁面不存在提示頁面。 58 * 3) 如果 onPageNotFound 回調中又重定向到另一個不存在的頁面,將推入微信客戶端原生的頁面不存在提示頁面,並且不再回調 onPageNotFound。 59 **/ 60 onPageNotFound : function(Object){ 61 this.errorPages = 2 // 采用this修改全局變量errorPages值 62 }, 63 64 65 /** 66 * 自定義其它類型數據,比如數組、JSON類 67 * 這類型數據為小程序所有頁面共享 68 **/ 69 errorPages : 0, 70 count : 1, 71 myArr : [1, 2, 3], 72 myJson : { 73 "title" : "hello world!" 74 } 75 })
getApp函數:
語法: getApp(Object)
說明: 獲取App內定義的相關數據,比如上例中的 count
參數: Object
Object.allowDefault [Boolean] 在 App 未定義時返回默認實現。當App被調用時,默認實現中定義的屬性會被覆蓋合並到App中。
注意:
1) 不要在定義於 App() 內的函數中調用 getApp() ,使用 this 就可以拿到 app 實例。
2) 通過 getApp() 獲取實例之后,不要私自調用生命周期函數。
示例:
比如要在頁面:index內調用App的全局變量,index.js示例代碼:
1 const app = getApp() 2 3 Page({ 4 onLoad: function () { 5 console.log( app.count ); 6 } 7 8 })