router.ts 1.6 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { App } from 'vue'
2 3 4
import {
  Router,
  RouterOptions,
fxy060608's avatar
fxy060608 已提交
5 6 7
  RouteRecordRaw,
  NavigationHookAfter,
  NavigationGuardWithThis,
8
} from 'vue-router'
fxy060608's avatar
fxy060608 已提交
9 10
import {
  createRouter,
11
  createWebHistory,
12
  createWebHashHistory,
fxy060608's avatar
fxy060608 已提交
13
} from 'vue-router'
fxy060608's avatar
fxy060608 已提交
14
import { getApp } from './app'
fxy060608's avatar
fxy060608 已提交
15 16

export function initRouter(app: App) {
fxy060608's avatar
fxy060608 已提交
17 18 19
  const router = createAppRouter(createRouter(createRouterOptions()))
  app.use(router)
  return router
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
}

const scrollBehavior: RouterOptions['scrollBehavior'] = (
  to,
  from,
  savedPosition
) => {
  if (savedPosition) {
    return savedPosition
  }
  // TODO tabBar?
}

function createRouterOptions(): RouterOptions {
  return {
fxy060608's avatar
fxy060608 已提交
35
    history: initHistory(),
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    strict: !!__uniConfig.router.strict,
    routes: __uniRoutes as RouteRecordRaw[],
    scrollBehavior,
  }
}

function initGuard(router: Router) {
  router.beforeEach(beforeEach)
  router.afterEach(afterEach)
}

function createAppRouter(router: Router) {
  initGuard(router)
  return router
}

fxy060608's avatar
fxy060608 已提交
52 53
function initHistory() {
  const history =
fxy060608's avatar
fxy060608 已提交
54
    __UNI_FEATURE_ROUTER_MODE__ === 'history'
fxy060608's avatar
fxy060608 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68
      ? createWebHistory()
      : createWebHashHistory()
  history.listen((_to, from, info) => {
    if (info.direction === 'back') {
      const app = getApp()
      const id = history.state.__id__
      if (app && id) {
        ;(app.$refs.app as any).keepAliveExclude = [from + '-' + id]
      }
    }
  })
  return history
}

69
const beforeEach: NavigationGuardWithThis<undefined> = (to, from, next) => {
fxy060608's avatar
fxy060608 已提交
70 71 72 73 74
  next()
}
const afterEach: NavigationHookAfter = (to, from, failure) => {
  console.log('afterEach.id', history.state.__id__)
  console.log('afterEach', to, from, failure, JSON.stringify(history.state))
fxy060608's avatar
fxy060608 已提交
75
}