route.js 1.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import {
fxy060608's avatar
fxy060608 已提交
2 3
  hasLifecycleHook
} from 'uni-helpers/index'
fxy060608's avatar
fxy060608 已提交
4 5 6 7

function onAppRoute (type, {
  url,
  delta,
fxy060608's avatar
fxy060608 已提交
8 9
  animationType,
  animationDuration,
fxy060608's avatar
fxy060608 已提交
10 11
  from = 'navigateBack',
  detail
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20 21 22 23
} = {}) {
  const router = getApp().$router
  switch (type) {
    case 'redirectTo':
      router.replace({
        type,
        path: url
      })
      break
    case 'navigateTo':
      router.push({
        type,
fxy060608's avatar
fxy060608 已提交
24 25 26
        path: url,
        animationType,
        animationDuration
fxy060608's avatar
fxy060608 已提交
27 28 29 30 31 32 33
      })
      break
    case 'navigateBack':
      let canBack = true
      const pages = getCurrentPages()
      if (pages.length) {
        const page = pages[pages.length - 1]
fxy060608's avatar
fxy060608 已提交
34
        if (hasLifecycleHook(page.$options, 'onBackPress') && page.__call_hook('onBackPress', {
fxy060608's avatar
fxy060608 已提交
35 36 37 38 39 40
          from
        }) === true) {
          canBack = false
        }
      }
      if (canBack) {
fxy060608's avatar
fxy060608 已提交
41 42 43
        if (delta > 1) {
          router._$delta = delta
        }
fxy060608's avatar
fxy060608 已提交
44 45 46 47
        router.go(-delta, {
          animationType,
          animationDuration
        })
fxy060608's avatar
fxy060608 已提交
48 49 50 51 52 53 54 55 56 57 58
      }
      break
    case 'reLaunch':
      router.replace({
        type,
        path: url
      })
      break
    case 'switchTab':
      router.replace({
        type,
fxy060608's avatar
fxy060608 已提交
59 60 61 62
        path: url,
        params: {
          detail
        }
fxy060608's avatar
fxy060608 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      })
      break
  }
  return {
    errMsg: type + ':ok'
  }
}

export function redirectTo (args) {
  return onAppRoute('redirectTo', args)
}

export function navigateTo (args) {
  return onAppRoute('navigateTo', args)
}

export function navigateBack (args) {
  return onAppRoute('navigateBack', args)
}

export function reLaunch (args) {
  return onAppRoute('reLaunch', args)
}

export function switchTab (args) {
  return onAppRoute('switchTab', args)
}