336c440b272e2f79dd6909515a82fc1fb9c68ef1632a298f1ebf4d59f82a3a583a590f00846665ce6ac3e34c06fe74adc8daf30a3e1988179f5cfe0c2ef169 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /* @flow */
  2. import { _Vue } from '../install'
  3. import type Router from '../index'
  4. import { inBrowser } from '../util/dom'
  5. import { runQueue } from '../util/async'
  6. import { warn } from '../util/warn'
  7. import { START, isSameRoute, handleRouteEntered } from '../util/route'
  8. import {
  9. flatten,
  10. flatMapComponents,
  11. resolveAsyncComponents
  12. } from '../util/resolve-components'
  13. import {
  14. createNavigationDuplicatedError,
  15. createNavigationCancelledError,
  16. createNavigationRedirectedError,
  17. createNavigationAbortedError,
  18. isError,
  19. isNavigationFailure,
  20. NavigationFailureType
  21. } from '../util/errors'
  22. export class History {
  23. router: Router
  24. base: string
  25. current: Route
  26. pending: ?Route
  27. cb: (r: Route) => void
  28. ready: boolean
  29. readyCbs: Array<Function>
  30. readyErrorCbs: Array<Function>
  31. errorCbs: Array<Function>
  32. listeners: Array<Function>
  33. cleanupListeners: Function
  34. // implemented by sub-classes
  35. +go: (n: number) => void
  36. +push: (loc: RawLocation, onComplete?: Function, onAbort?: Function) => void
  37. +replace: (
  38. loc: RawLocation,
  39. onComplete?: Function,
  40. onAbort?: Function
  41. ) => void
  42. +ensureURL: (push?: boolean) => void
  43. +getCurrentLocation: () => string
  44. +setupListeners: Function
  45. constructor (router: Router, base: ?string) {
  46. this.router = router
  47. this.base = normalizeBase(base)
  48. // start with a route object that stands for "nowhere"
  49. this.current = START
  50. this.pending = null
  51. this.ready = false
  52. this.readyCbs = []
  53. this.readyErrorCbs = []
  54. this.errorCbs = []
  55. this.listeners = []
  56. }
  57. listen (cb: Function) {
  58. this.cb = cb
  59. }
  60. onReady (cb: Function, errorCb: ?Function) {
  61. if (this.ready) {
  62. cb()
  63. } else {
  64. this.readyCbs.push(cb)
  65. if (errorCb) {
  66. this.readyErrorCbs.push(errorCb)
  67. }
  68. }
  69. }
  70. onError (errorCb: Function) {
  71. this.errorCbs.push(errorCb)
  72. }
  73. transitionTo (
  74. location: RawLocation,
  75. onComplete?: Function,
  76. onAbort?: Function
  77. ) {
  78. let route
  79. // catch redirect option https://github.com/vuejs/vue-router/issues/3201
  80. try {
  81. route = this.router.match(location, this.current)
  82. } catch (e) {
  83. this.errorCbs.forEach(cb => {
  84. cb(e)
  85. })
  86. // Exception should still be thrown
  87. throw e
  88. }
  89. const prev = this.current
  90. this.confirmTransition(
  91. route,
  92. () => {
  93. this.updateRoute(route)
  94. onComplete && onComplete(route)
  95. this.ensureURL()
  96. this.router.afterHooks.forEach(hook => {
  97. hook && hook(route, prev)
  98. })
  99. // fire ready cbs once
  100. if (!this.ready) {
  101. this.ready = true
  102. this.readyCbs.forEach(cb => {
  103. cb(route)
  104. })
  105. }
  106. },
  107. err => {
  108. if (onAbort) {
  109. onAbort(err)
  110. }
  111. if (err && !this.ready) {
  112. // Initial redirection should not mark the history as ready yet
  113. // because it's triggered by the redirection instead
  114. // https://github.com/vuejs/vue-router/issues/3225
  115. // https://github.com/vuejs/vue-router/issues/3331
  116. if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
  117. this.ready = true
  118. this.readyErrorCbs.forEach(cb => {
  119. cb(err)
  120. })
  121. }
  122. }
  123. }
  124. )
  125. }
  126. confirmTransition (route: Route, onComplete: Function, onAbort?: Function) {
  127. const current = this.current
  128. this.pending = route
  129. const abort = err => {
  130. // changed after adding errors with
  131. // https://github.com/vuejs/vue-router/pull/3047 before that change,
  132. // redirect and aborted navigation would produce an err == null
  133. if (!isNavigationFailure(err) && isError(err)) {
  134. if (this.errorCbs.length) {
  135. this.errorCbs.forEach(cb => {
  136. cb(err)
  137. })
  138. } else {
  139. warn(false, 'uncaught error during route navigation:')
  140. console.error(err)
  141. }
  142. }
  143. onAbort && onAbort(err)
  144. }
  145. const lastRouteIndex = route.matched.length - 1
  146. const lastCurrentIndex = current.matched.length - 1
  147. if (
  148. isSameRoute(route, current) &&
  149. // in the case the route map has been dynamically appended to
  150. lastRouteIndex === lastCurrentIndex &&
  151. route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
  152. ) {
  153. this.ensureURL()
  154. return abort(createNavigationDuplicatedError(current, route))
  155. }
  156. const { updated, deactivated, activated } = resolveQueue(
  157. this.current.matched,
  158. route.matched
  159. )
  160. const queue: Array<?NavigationGuard> = [].concat(
  161. // in-component leave guards
  162. extractLeaveGuards(deactivated),
  163. // global before hooks
  164. this.router.beforeHooks,
  165. // in-component update hooks
  166. extractUpdateHooks(updated),
  167. // in-config enter guards
  168. activated.map(m => m.beforeEnter),
  169. // async components
  170. resolveAsyncComponents(activated)
  171. )
  172. const iterator = (hook: NavigationGuard, next) => {
  173. if (this.pending !== route) {
  174. return abort(createNavigationCancelledError(current, route))
  175. }
  176. try {
  177. hook(route, current, (to: any) => {
  178. if (to === false) {
  179. // next(false) -> abort navigation, ensure current URL
  180. this.ensureURL(true)
  181. abort(createNavigationAbortedError(current, route))
  182. } else if (isError(to)) {
  183. this.ensureURL(true)
  184. abort(to)
  185. } else if (
  186. typeof to === 'string' ||
  187. (typeof to === 'object' &&
  188. (typeof to.path === 'string' || typeof to.name === 'string'))
  189. ) {
  190. // next('/') or next({ path: '/' }) -> redirect
  191. abort(createNavigationRedirectedError(current, route))
  192. if (typeof to === 'object' && to.replace) {
  193. this.replace(to)
  194. } else {
  195. this.push(to)
  196. }
  197. } else {
  198. // confirm transition and pass on the value
  199. next(to)
  200. }
  201. })
  202. } catch (e) {
  203. abort(e)
  204. }
  205. }
  206. runQueue(queue, iterator, () => {
  207. // wait until async components are resolved before
  208. // extracting in-component enter guards
  209. const enterGuards = extractEnterGuards(activated)
  210. const queue = enterGuards.concat(this.router.resolveHooks)
  211. runQueue(queue, iterator, () => {
  212. if (this.pending !== route) {
  213. return abort(createNavigationCancelledError(current, route))
  214. }
  215. this.pending = null
  216. onComplete(route)
  217. if (this.router.app) {
  218. this.router.app.$nextTick(() => {
  219. handleRouteEntered(route)
  220. })
  221. }
  222. })
  223. })
  224. }
  225. updateRoute (route: Route) {
  226. this.current = route
  227. this.cb && this.cb(route)
  228. }
  229. setupListeners () {
  230. // Default implementation is empty
  231. }
  232. teardown () {
  233. // clean up event listeners
  234. // https://github.com/vuejs/vue-router/issues/2341
  235. this.listeners.forEach(cleanupListener => {
  236. cleanupListener()
  237. })
  238. this.listeners = []
  239. // reset current history route
  240. // https://github.com/vuejs/vue-router/issues/3294
  241. this.current = START
  242. this.pending = null
  243. }
  244. }
  245. function normalizeBase (base: ?string): string {
  246. if (!base) {
  247. if (inBrowser) {
  248. // respect <base> tag
  249. const baseEl = document.querySelector('base')
  250. base = (baseEl && baseEl.getAttribute('href')) || '/'
  251. // strip full URL origin
  252. base = base.replace(/^https?:\/\/[^\/]+/, '')
  253. } else {
  254. base = '/'
  255. }
  256. }
  257. // make sure there's the starting slash
  258. if (base.charAt(0) !== '/') {
  259. base = '/' + base
  260. }
  261. // remove trailing slash
  262. return base.replace(/\/$/, '')
  263. }
  264. function resolveQueue (
  265. current: Array<RouteRecord>,
  266. next: Array<RouteRecord>
  267. ): {
  268. updated: Array<RouteRecord>,
  269. activated: Array<RouteRecord>,
  270. deactivated: Array<RouteRecord>
  271. } {
  272. let i
  273. const max = Math.max(current.length, next.length)
  274. for (i = 0; i < max; i++) {
  275. if (current[i] !== next[i]) {
  276. break
  277. }
  278. }
  279. return {
  280. updated: next.slice(0, i),
  281. activated: next.slice(i),
  282. deactivated: current.slice(i)
  283. }
  284. }
  285. function extractGuards (
  286. records: Array<RouteRecord>,
  287. name: string,
  288. bind: Function,
  289. reverse?: boolean
  290. ): Array<?Function> {
  291. const guards = flatMapComponents(records, (def, instance, match, key) => {
  292. const guard = extractGuard(def, name)
  293. if (guard) {
  294. return Array.isArray(guard)
  295. ? guard.map(guard => bind(guard, instance, match, key))
  296. : bind(guard, instance, match, key)
  297. }
  298. })
  299. return flatten(reverse ? guards.reverse() : guards)
  300. }
  301. function extractGuard (
  302. def: Object | Function,
  303. key: string
  304. ): NavigationGuard | Array<NavigationGuard> {
  305. if (typeof def !== 'function') {
  306. // extend now so that global mixins are applied.
  307. def = _Vue.extend(def)
  308. }
  309. return def.options[key]
  310. }
  311. function extractLeaveGuards (deactivated: Array<RouteRecord>): Array<?Function> {
  312. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  313. }
  314. function extractUpdateHooks (updated: Array<RouteRecord>): Array<?Function> {
  315. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  316. }
  317. function bindGuard (guard: NavigationGuard, instance: ?_Vue): ?NavigationGuard {
  318. if (instance) {
  319. return function boundRouteGuard () {
  320. return guard.apply(instance, arguments)
  321. }
  322. }
  323. }
  324. function extractEnterGuards (
  325. activated: Array<RouteRecord>
  326. ): Array<?Function> {
  327. return extractGuards(
  328. activated,
  329. 'beforeRouteEnter',
  330. (guard, _, match, key) => {
  331. return bindEnterGuard(guard, match, key)
  332. }
  333. )
  334. }
  335. function bindEnterGuard (
  336. guard: NavigationGuard,
  337. match: RouteRecord,
  338. key: string
  339. ): NavigationGuard {
  340. return function routeEnterGuard (to, from, next) {
  341. return guard(to, from, cb => {
  342. if (typeof cb === 'function') {
  343. if (!match.enteredCbs[key]) {
  344. match.enteredCbs[key] = []
  345. }
  346. match.enteredCbs[key].push(cb)
  347. }
  348. next(cb)
  349. })
  350. }
  351. }