App.js是項目的入口文件,頁面的 page.js 文件會覆蓋 app.js文件,
App.js是整個小程序項目的入口文件,也就是說,如果小程序要運行,第一個被執行的文件就是app.js,在app.js中可以書寫小程序的全局業務邏輯。
app.js作用
一:小程序要運行,第一個被執行的文件是app.js,第一個被執行的代碼時app.js中的onLaunch方法
App.js文件里面的一些方法:
onLaunch : function(){}:這個方法是當小程序加載完畢后就執行的方法
onLoad:function(options){}:頁面初始化 options 為頁面跳轉所傳遞過來的參數
onReady:function(){}:頁面渲染完成
onShow:function(){}:頁面顯示
onHide:function(){}:頁面隱藏
onUnload:function(){}:頁面關閉
二、在app.js里面,寫上一些需要的東西,如globalData,在其他頁面需要時,可以直接調用,無需一直寫!
案例:
1、app.js代碼如下
//app.js App({ globalData: { serverApi: "http://10.144.116.207:8008", staticApi: "http://10.144.116.207:8008/uploadPath", userInfo: null, token: null }, getMenuList: function(list) { var menuList = []; list.forEach((item, index) => { var id = item.id; var name = item.name; var parentId = item.parentId; if (parentId == 0 && name != '首頁') { //過濾平台的首頁 //第一層級 item.children = []; item.hidden = true; list.forEach((jtem, jndex) => { var parentId2 = jtem.parentId; if (parentId2 == id) { //第二層級 item.children.push(jtem); } }); menuList.push(item); } }); return menuList; }, onLaunch: function () { // 展示本地存儲能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) // 登錄 wx.login({ success: res => { // 發送 res.code 到后台換取 openId 驗證平台賬號是否登錄綁定過 var that = this; wx.request({ method: 'GET', url: this.globalData.serverApi + "/mobileApi/user/checkBind?code="+res.code, header: { 'content-type': 'application/json' }, success (res) { if(res.data.code == 301){ //未登錄 var openId = res.data.openId; wx.reLaunch({ url: '/pages/login/login?openId='+openId }) }else if(res.data.code == 1){ //已登錄 that.globalData.userInfo = res.data.userInfo; that.globalData.token = res.data.token; var menuList = res.data.menuList; wx.setStorageSync('menuList', that.getMenuList(menuList)); }else if(res.data.code == 0){ //獲取openId失敗 wx.showToast({ title: res.data.msg, icon: 'none', duration: 2000 }) } // 由於 checkBind 是網絡請求,可能會在 Page.onLoad 之后才返回 // 所以此處加入 callback 以防止這種情況 if (that.checkBindCallback) { that.checkBindCallback(res) } } }) } }) }, })
app.js文件的使用
通過const app = getApp()實現在 page 頁面獲取 app.js,從而獲取app.js中定義的全局數據globalData
獲取全局數據globalData
在頁面的index.js開頭寫上,然后就可以在page里面的onLoad()里調用你需要的東西!
//index.js //獲取應用實例 const app = getApp() Page({ onLoad: function () { if(app.globalData.token){ //代表從頁面跳轉過來 var menuList = wx.getStorageSync('menuList'); this.getMenuList(menuList); this.animation = wx.createAnimation(); this.setData({hidden: false}); }else{ //代表第一次加載 wx.showLoading({ title: '加載中' }) // 由於 checkBind 是網絡請求,可能會在 Page.onLoad 之后才返回 // 所以此處加入 callback 以防止這種情況 app.checkBindCallback = res => { wx.hideLoading(); if(res.data.code == 1){ var menuList = wx.getStorageSync('menuList'); this.getMenuList(menuList); this.animation = wx.createAnimation(); this.setData({hidden: false}); } } } } })