create-app.js 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8
import initRouterGuard from './router-guard'

let appVm = false

export function getApp () {
  return appVm
}

9
export function getCurrentPages (isAll = false, ignoreError = false) {
fxy060608's avatar
fxy060608 已提交
10
  const pages = []
11
  const app = getApp()
12
  if (!app) {
13 14 15
    if (ignoreError) {
      console.error('app is not ready')
    }
16 17
    return []
  }
18
  const childrenVm = app.$children[0]
fxy060608's avatar
fxy060608 已提交
19 20
  if (childrenVm && childrenVm.$children.length) {
    const tabBarVm = childrenVm.$children.find(vm => vm.$options.name === 'TabBar')
21

fxy060608's avatar
fxy060608 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    childrenVm.$children.forEach(vm => {
      if (tabBarVm !== vm && vm.$children.length && vm.$children[0].$options.name === 'Page' && vm.$children[0].$slots.page) {
        // vm.$children[0]=Page->PageBody->RealPage
        const pageVm = vm.$children[0].$children.find(vm => vm.$options.name === 'PageBody').$children.find(vm => !!vm.$page)
        if (pageVm) {
          let isActive = true
          if (!isAll && tabBarVm && pageVm.$page && pageVm.$page.meta.isTabBar) { // 选项卡仅列出活动的
            if (app.$route.meta && app.$route.meta.isTabBar) { // 当前页面路由是 tabBar
              if (app.$route.path !== pageVm.$page.path) {
                isActive = false
              }
            } else {
              if (tabBarVm.__path__ !== pageVm.$page.path) {
                isActive = false
              }
            }
          }
          if (isActive) {
            pages.push(pageVm)
          }
        } else {
          // TODO
          // console.error('pageVm is undefined')
        }
      }
    })
  }
49 50 51 52 53 54 55
  // 当页面返回过程中,请求 getCurrentPages 时,可能会获取到前一个已经准备销毁的 page
  const length = pages.length
  if (length > 1) {
    const currentPage = pages[length - 1]
    if (currentPage.$page.path !== app.$route.path) { // 删除已经准备销毁的上个页面
      pages.splice(length - 1, 1)
    }
56
  }
57

fxy060608's avatar
fxy060608 已提交
58 59 60 61 62 63 64 65 66
  return pages
}

export default function createApp (vm, routes) {
  appVm = vm
  appVm.globalData = appVm.$options.globalData || {}

  // initEvents(appVm)
  initRouterGuard(appVm, routes)
67
}