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}); } } } } })