index.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /* @flow */
  2. import { install } from './install'
  3. import { START } from './util/route'
  4. import { assert } from './util/warn'
  5. import { inBrowser } from './util/dom'
  6. import { cleanPath } from './util/path'
  7. import { createMatcher } from './create-matcher'
  8. import { normalizeLocation } from './util/location'
  9. import { supportsPushState } from './util/push-state'
  10. import { handleScroll } from './util/scroll'
  11. import { HashHistory } from './history/hash'
  12. import { HTML5History } from './history/html5'
  13. import { AbstractHistory } from './history/abstract'
  14. import type { Matcher } from './create-matcher'
  15. import { isNavigationFailure, NavigationFailureType } from './util/errors'
  16. export default class VueRouter {
  17. static install: () => void
  18. static version: string
  19. static isNavigationFailure: Function
  20. static NavigationFailureType: any
  21. app: any
  22. apps: Array<any>
  23. ready: boolean
  24. readyCbs: Array<Function>
  25. options: RouterOptions
  26. mode: string
  27. history: HashHistory | HTML5History | AbstractHistory
  28. matcher: Matcher
  29. fallback: boolean
  30. beforeHooks: Array<?NavigationGuard>
  31. resolveHooks: Array<?NavigationGuard>
  32. afterHooks: Array<?AfterNavigationHook>
  33. constructor (options: RouterOptions = {}) {
  34. this.app = null
  35. this.apps = []
  36. this.options = options
  37. this.beforeHooks = []
  38. this.resolveHooks = []
  39. this.afterHooks = []
  40. this.matcher = createMatcher(options.routes || [], this)
  41. let mode = options.mode || 'hash'
  42. this.fallback =
  43. mode === 'history' && !supportsPushState && options.fallback !== false
  44. if (this.fallback) {
  45. mode = 'hash'
  46. }
  47. if (!inBrowser) {
  48. mode = 'abstract'
  49. }
  50. this.mode = mode
  51. switch (mode) {
  52. case 'history':
  53. this.history = new HTML5History(this, options.base)
  54. break
  55. case 'hash':
  56. this.history = new HashHistory(this, options.base, this.fallback)
  57. break
  58. case 'abstract':
  59. this.history = new AbstractHistory(this, options.base)
  60. break
  61. default:
  62. if (process.env.NODE_ENV !== 'production') {
  63. assert(false, `invalid mode: ${mode}`)
  64. }
  65. }
  66. }
  67. match (raw: RawLocation, current?: Route, redirectedFrom?: Location): Route {
  68. return this.matcher.match(raw, current, redirectedFrom)
  69. }
  70. get currentRoute (): ?Route {
  71. return this.history && this.history.current
  72. }
  73. init (app: any /* Vue component instance */) {
  74. process.env.NODE_ENV !== 'production' &&
  75. assert(
  76. install.installed,
  77. `not installed. Make sure to call \`Vue.use(VueRouter)\` ` +
  78. `before creating root instance.`
  79. )
  80. this.apps.push(app)
  81. // set up app destroyed handler
  82. // https://github.com/vuejs/vue-router/issues/2639
  83. app.$once('hook:destroyed', () => {
  84. // clean out app from this.apps array once destroyed
  85. const index = this.apps.indexOf(app)
  86. if (index > -1) this.apps.splice(index, 1)
  87. // ensure we still have a main app or null if no apps
  88. // we do not release the router so it can be reused
  89. if (this.app === app) this.app = this.apps[0] || null
  90. if (!this.app) this.history.teardown()
  91. })
  92. // main app previously initialized
  93. // return as we don't need to set up new history listener
  94. if (this.app) {
  95. return
  96. }
  97. this.app = app
  98. const history = this.history
  99. if (history instanceof HTML5History || history instanceof HashHistory) {
  100. const handleInitialScroll = routeOrError => {
  101. const from = history.current
  102. const expectScroll = this.options.scrollBehavior
  103. const supportsScroll = supportsPushState && expectScroll
  104. if (supportsScroll && 'fullPath' in routeOrError) {
  105. handleScroll(this, routeOrError, from, false)
  106. }
  107. }
  108. const setupListeners = routeOrError => {
  109. history.setupListeners()
  110. handleInitialScroll(routeOrError)
  111. }
  112. history.transitionTo(
  113. history.getCurrentLocation(),
  114. setupListeners,
  115. setupListeners
  116. )
  117. }
  118. history.listen(route => {
  119. this.apps.forEach(app => {
  120. app._route = route
  121. })
  122. })
  123. }
  124. beforeEach (fn: Function): Function {
  125. return registerHook(this.beforeHooks, fn)
  126. }
  127. beforeResolve (fn: Function): Function {
  128. return registerHook(this.resolveHooks, fn)
  129. }
  130. afterEach (fn: Function): Function {
  131. return registerHook(this.afterHooks, fn)
  132. }
  133. onReady (cb: Function, errorCb?: Function) {
  134. this.history.onReady(cb, errorCb)
  135. }
  136. onError (errorCb: Function) {
  137. this.history.onError(errorCb)
  138. }
  139. push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
  140. // $flow-disable-line
  141. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  142. return new Promise((resolve, reject) => {
  143. this.history.push(location, resolve, reject)
  144. })
  145. } else {
  146. this.history.push(location, onComplete, onAbort)
  147. }
  148. }
  149. replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {
  150. // $flow-disable-line
  151. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  152. return new Promise((resolve, reject) => {
  153. this.history.replace(location, resolve, reject)
  154. })
  155. } else {
  156. this.history.replace(location, onComplete, onAbort)
  157. }
  158. }
  159. go (n: number) {
  160. this.history.go(n)
  161. }
  162. back () {
  163. this.go(-1)
  164. }
  165. forward () {
  166. this.go(1)
  167. }
  168. getMatchedComponents (to?: RawLocation | Route): Array<any> {
  169. const route: any = to
  170. ? to.matched
  171. ? to
  172. : this.resolve(to).route
  173. : this.currentRoute
  174. if (!route) {
  175. return []
  176. }
  177. return [].concat.apply(
  178. [],
  179. route.matched.map(m => {
  180. return Object.keys(m.components).map(key => {
  181. return m.components[key]
  182. })
  183. })
  184. )
  185. }
  186. resolve (
  187. to: RawLocation,
  188. current?: Route,
  189. append?: boolean
  190. ): {
  191. location: Location,
  192. route: Route,
  193. href: string,
  194. // for backwards compat
  195. normalizedTo: Location,
  196. resolved: Route
  197. } {
  198. current = current || this.history.current
  199. const location = normalizeLocation(to, current, append, this)
  200. const route = this.match(location, current)
  201. const fullPath = route.redirectedFrom || route.fullPath
  202. const base = this.history.base
  203. const href = createHref(base, fullPath, this.mode)
  204. return {
  205. location,
  206. route,
  207. href,
  208. // for backwards compat
  209. normalizedTo: location,
  210. resolved: route
  211. }
  212. }
  213. addRoutes (routes: Array<RouteConfig>) {
  214. this.matcher.addRoutes(routes)
  215. if (this.history.current !== START) {
  216. this.history.transitionTo(this.history.getCurrentLocation())
  217. }
  218. }
  219. }
  220. function registerHook (list: Array<any>, fn: Function): Function {
  221. list.push(fn)
  222. return () => {
  223. const i = list.indexOf(fn)
  224. if (i > -1) list.splice(i, 1)
  225. }
  226. }
  227. function createHref (base: string, fullPath: string, mode) {
  228. var path = mode === 'hash' ? '#' + fullPath : fullPath
  229. return base ? cleanPath(base + '/' + path) : path
  230. }
  231. VueRouter.install = install
  232. VueRouter.version = '__VERSION__'
  233. VueRouter.isNavigationFailure = isNavigationFailure
  234. VueRouter.NavigationFailureType = NavigationFailureType
  235. if (inBrowser && window.Vue) {
  236. window.Vue.use(VueRouter)
  237. }