loading.js 2.43 KB
// pages/loading/loading.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log('---------------- 页面初始化 ----------------')
    console.log('options参数:', options)
    this.tabList = __wxConfig?.tabBar?.list || []
    wx.p.wxApi.showLoading()
    //scenc获取页面参数并跳转
    if (options.scene) {
      return this.getSceneById(options.scene)
    }
    if (options.url) {
      return this.login(options)
    }
    this.login()
  },
  async login(options = {}) {
    try {
      const userInfo = wx.p.storage.get('userInfo')
      if (!userInfo.beiSenToken) wx.p.router.goHome(this.options)
      else {
        wx.p.wxApi.hideLoading()
        wx.$LoginStatus = false
        if (options.url) return this.jumpPage(options.url)
        wx.p.router.reLaunch('/packageIndex/pages/index/index', this.options)
      }
    } catch (error) {
      wx.p.wxApi.hideLoading()
      wx.$LoginStatus = true //请求失败默认未登录
      if (error) wx.p.wxApi.showToast(String(error))
      wx.p.router.goHome(this.options)
    }
  },
  async getSceneById(scene) {
    const id = decodeURIComponent(scene).split('=').at(-1)
    try {
      const {
        code,
        data
      } = await wx.p.api.wechatApi.getSceneById({
        id
      })
      const params = data.scene.split('url='),
        options = {}
      if (params.length > 1) options.url = params.at(-1)
      if (code == 0) this.login(options)
      else throw {}
    } catch (error) {
      wx.p.wxApi.showToast(error || '获取scene失败')
      this.login()
    }
  },
  jumpPage(val) {
    const targetPath = decodeURIComponent(val),
      {
        url,
        events
      } = this.setRouteData(targetPath),

      routeName = this.tabList.findIndex(e => `/${e.pagePath}` == `${url}.html`) > -1 ? 'switchTab' : 'redirectTo'
    events.notIntercept = true
    wx.p.router[routeName](url, events)
  },
  setRouteData(targetPath) {
    let [url, query] = targetPath.split('?'),
      events = {}
    if (query) {
      let arr = query.split('&')
      arr.map(e => {
        let [key, val] = e.split('=')
        if (val == 'false' || val == 'true') val = JSON.parse(val)
        Object.assign(events, {
          [key]: val
        })
      })
    }
    return {
      url,
      events
    }
  }
})