vue-router.esm.browser.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. /*!
  2. * vue-router v3.0.6
  3. * (c) 2019 Evan You
  4. * @license MIT
  5. */
  6. /* */
  7. function assert (condition, message) {
  8. if (!condition) {
  9. throw new Error(`[vue-router] ${message}`)
  10. }
  11. }
  12. function warn (condition, message) {
  13. if ("development" !== 'production' && !condition) {
  14. typeof console !== 'undefined' && console.warn(`[vue-router] ${message}`);
  15. }
  16. }
  17. function isError (err) {
  18. return Object.prototype.toString.call(err).indexOf('Error') > -1
  19. }
  20. function extend (a, b) {
  21. for (const key in b) {
  22. a[key] = b[key];
  23. }
  24. return a
  25. }
  26. var View = {
  27. name: 'RouterView',
  28. functional: true,
  29. props: {
  30. name: {
  31. type: String,
  32. default: 'default'
  33. }
  34. },
  35. render (_, { props, children, parent, data }) {
  36. // used by devtools to display a router-view badge
  37. data.routerView = true;
  38. // directly use parent context's createElement() function
  39. // so that components rendered by router-view can resolve named slots
  40. const h = parent.$createElement;
  41. const name = props.name;
  42. const route = parent.$route;
  43. const cache = parent._routerViewCache || (parent._routerViewCache = {});
  44. // determine current view depth, also check to see if the tree
  45. // has been toggled inactive but kept-alive.
  46. let depth = 0;
  47. let inactive = false;
  48. while (parent && parent._routerRoot !== parent) {
  49. const vnodeData = parent.$vnode && parent.$vnode.data;
  50. if (vnodeData) {
  51. if (vnodeData.routerView) {
  52. depth++;
  53. }
  54. if (vnodeData.keepAlive && parent._inactive) {
  55. inactive = true;
  56. }
  57. }
  58. parent = parent.$parent;
  59. }
  60. data.routerViewDepth = depth;
  61. // render previous view if the tree is inactive and kept-alive
  62. if (inactive) {
  63. return h(cache[name], data, children)
  64. }
  65. const matched = route.matched[depth];
  66. // render empty node if no matched route
  67. if (!matched) {
  68. cache[name] = null;
  69. return h()
  70. }
  71. const component = cache[name] = matched.components[name];
  72. // attach instance registration hook
  73. // this will be called in the instance's injected lifecycle hooks
  74. data.registerRouteInstance = (vm, val) => {
  75. // val could be undefined for unregistration
  76. const current = matched.instances[name];
  77. if (
  78. (val && current !== vm) ||
  79. (!val && current === vm)
  80. ) {
  81. matched.instances[name] = val;
  82. }
  83. }
  84. // also register instance in prepatch hook
  85. // in case the same component instance is reused across different routes
  86. ;(data.hook || (data.hook = {})).prepatch = (_, vnode) => {
  87. matched.instances[name] = vnode.componentInstance;
  88. };
  89. // register instance in init hook
  90. // in case kept-alive component be actived when routes changed
  91. data.hook.init = (vnode) => {
  92. if (vnode.data.keepAlive &&
  93. vnode.componentInstance &&
  94. vnode.componentInstance !== matched.instances[name]
  95. ) {
  96. matched.instances[name] = vnode.componentInstance;
  97. }
  98. };
  99. // resolve props
  100. let propsToPass = data.props = resolveProps(route, matched.props && matched.props[name]);
  101. if (propsToPass) {
  102. // clone to prevent mutation
  103. propsToPass = data.props = extend({}, propsToPass);
  104. // pass non-declared props as attrs
  105. const attrs = data.attrs = data.attrs || {};
  106. for (const key in propsToPass) {
  107. if (!component.props || !(key in component.props)) {
  108. attrs[key] = propsToPass[key];
  109. delete propsToPass[key];
  110. }
  111. }
  112. }
  113. return h(component, data, children)
  114. }
  115. }
  116. function resolveProps (route, config) {
  117. switch (typeof config) {
  118. case 'undefined':
  119. return
  120. case 'object':
  121. return config
  122. case 'function':
  123. return config(route)
  124. case 'boolean':
  125. return config ? route.params : undefined
  126. default:
  127. {
  128. warn(
  129. false,
  130. `props in "${route.path}" is a ${typeof config}, ` +
  131. `expecting an object, function or boolean.`
  132. );
  133. }
  134. }
  135. }
  136. /* */
  137. const encodeReserveRE = /[!'()*]/g;
  138. const encodeReserveReplacer = c => '%' + c.charCodeAt(0).toString(16);
  139. const commaRE = /%2C/g;
  140. // fixed encodeURIComponent which is more conformant to RFC3986:
  141. // - escapes [!'()*]
  142. // - preserve commas
  143. const encode = str => encodeURIComponent(str)
  144. .replace(encodeReserveRE, encodeReserveReplacer)
  145. .replace(commaRE, ',');
  146. const decode = decodeURIComponent;
  147. function resolveQuery (
  148. query,
  149. extraQuery = {},
  150. _parseQuery
  151. ) {
  152. const parse = _parseQuery || parseQuery;
  153. let parsedQuery;
  154. try {
  155. parsedQuery = parse(query || '');
  156. } catch (e) {
  157. "development" !== 'production' && warn(false, e.message);
  158. parsedQuery = {};
  159. }
  160. for (const key in extraQuery) {
  161. parsedQuery[key] = extraQuery[key];
  162. }
  163. return parsedQuery
  164. }
  165. function parseQuery (query) {
  166. const res = {};
  167. query = query.trim().replace(/^(\?|#|&)/, '');
  168. if (!query) {
  169. return res
  170. }
  171. query.split('&').forEach(param => {
  172. const parts = param.replace(/\+/g, ' ').split('=');
  173. const key = decode(parts.shift());
  174. const val = parts.length > 0
  175. ? decode(parts.join('='))
  176. : null;
  177. if (res[key] === undefined) {
  178. res[key] = val;
  179. } else if (Array.isArray(res[key])) {
  180. res[key].push(val);
  181. } else {
  182. res[key] = [res[key], val];
  183. }
  184. });
  185. return res
  186. }
  187. function stringifyQuery (obj) {
  188. const res = obj ? Object.keys(obj).map(key => {
  189. const val = obj[key];
  190. if (val === undefined) {
  191. return ''
  192. }
  193. if (val === null) {
  194. return encode(key)
  195. }
  196. if (Array.isArray(val)) {
  197. const result = [];
  198. val.forEach(val2 => {
  199. if (val2 === undefined) {
  200. return
  201. }
  202. if (val2 === null) {
  203. result.push(encode(key));
  204. } else {
  205. result.push(encode(key) + '=' + encode(val2));
  206. }
  207. });
  208. return result.join('&')
  209. }
  210. return encode(key) + '=' + encode(val)
  211. }).filter(x => x.length > 0).join('&') : null;
  212. return res ? `?${res}` : ''
  213. }
  214. /* */
  215. const trailingSlashRE = /\/?$/;
  216. function createRoute (
  217. record,
  218. location,
  219. redirectedFrom,
  220. router
  221. ) {
  222. const stringifyQuery$$1 = router && router.options.stringifyQuery;
  223. let query = location.query || {};
  224. try {
  225. query = clone(query);
  226. } catch (e) {}
  227. const route = {
  228. name: location.name || (record && record.name),
  229. meta: (record && record.meta) || {},
  230. path: location.path || '/',
  231. hash: location.hash || '',
  232. query,
  233. params: location.params || {},
  234. fullPath: getFullPath(location, stringifyQuery$$1),
  235. matched: record ? formatMatch(record) : []
  236. };
  237. if (redirectedFrom) {
  238. route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery$$1);
  239. }
  240. return Object.freeze(route)
  241. }
  242. function clone (value) {
  243. if (Array.isArray(value)) {
  244. return value.map(clone)
  245. } else if (value && typeof value === 'object') {
  246. const res = {};
  247. for (const key in value) {
  248. res[key] = clone(value[key]);
  249. }
  250. return res
  251. } else {
  252. return value
  253. }
  254. }
  255. // the starting route that represents the initial state
  256. const START = createRoute(null, {
  257. path: '/'
  258. });
  259. function formatMatch (record) {
  260. const res = [];
  261. while (record) {
  262. res.unshift(record);
  263. record = record.parent;
  264. }
  265. return res
  266. }
  267. function getFullPath (
  268. { path, query = {}, hash = '' },
  269. _stringifyQuery
  270. ) {
  271. const stringify = _stringifyQuery || stringifyQuery;
  272. return (path || '/') + stringify(query) + hash
  273. }
  274. function isSameRoute (a, b) {
  275. if (b === START) {
  276. return a === b
  277. } else if (!b) {
  278. return false
  279. } else if (a.path && b.path) {
  280. return (
  281. a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
  282. a.hash === b.hash &&
  283. isObjectEqual(a.query, b.query)
  284. )
  285. } else if (a.name && b.name) {
  286. return (
  287. a.name === b.name &&
  288. a.hash === b.hash &&
  289. isObjectEqual(a.query, b.query) &&
  290. isObjectEqual(a.params, b.params)
  291. )
  292. } else {
  293. return false
  294. }
  295. }
  296. function isObjectEqual (a = {}, b = {}) {
  297. // handle null value #1566
  298. if (!a || !b) return a === b
  299. const aKeys = Object.keys(a);
  300. const bKeys = Object.keys(b);
  301. if (aKeys.length !== bKeys.length) {
  302. return false
  303. }
  304. return aKeys.every(key => {
  305. const aVal = a[key];
  306. const bVal = b[key];
  307. // check nested equality
  308. if (typeof aVal === 'object' && typeof bVal === 'object') {
  309. return isObjectEqual(aVal, bVal)
  310. }
  311. return String(aVal) === String(bVal)
  312. })
  313. }
  314. function isIncludedRoute (current, target) {
  315. return (
  316. current.path.replace(trailingSlashRE, '/').indexOf(
  317. target.path.replace(trailingSlashRE, '/')
  318. ) === 0 &&
  319. (!target.hash || current.hash === target.hash) &&
  320. queryIncludes(current.query, target.query)
  321. )
  322. }
  323. function queryIncludes (current, target) {
  324. for (const key in target) {
  325. if (!(key in current)) {
  326. return false
  327. }
  328. }
  329. return true
  330. }
  331. /* */
  332. // work around weird flow bug
  333. const toTypes = [String, Object];
  334. const eventTypes = [String, Array];
  335. var Link = {
  336. name: 'RouterLink',
  337. props: {
  338. to: {
  339. type: toTypes,
  340. required: true
  341. },
  342. tag: {
  343. type: String,
  344. default: 'a'
  345. },
  346. exact: Boolean,
  347. append: Boolean,
  348. replace: Boolean,
  349. activeClass: String,
  350. exactActiveClass: String,
  351. event: {
  352. type: eventTypes,
  353. default: 'click'
  354. }
  355. },
  356. render (h) {
  357. const router = this.$router;
  358. const current = this.$route;
  359. const { location, route, href } = router.resolve(this.to, current, this.append);
  360. const classes = {};
  361. const globalActiveClass = router.options.linkActiveClass;
  362. const globalExactActiveClass = router.options.linkExactActiveClass;
  363. // Support global empty active class
  364. const activeClassFallback = globalActiveClass == null
  365. ? 'router-link-active'
  366. : globalActiveClass;
  367. const exactActiveClassFallback = globalExactActiveClass == null
  368. ? 'router-link-exact-active'
  369. : globalExactActiveClass;
  370. const activeClass = this.activeClass == null
  371. ? activeClassFallback
  372. : this.activeClass;
  373. const exactActiveClass = this.exactActiveClass == null
  374. ? exactActiveClassFallback
  375. : this.exactActiveClass;
  376. const compareTarget = location.path
  377. ? createRoute(null, location, null, router)
  378. : route;
  379. classes[exactActiveClass] = isSameRoute(current, compareTarget);
  380. classes[activeClass] = this.exact
  381. ? classes[exactActiveClass]
  382. : isIncludedRoute(current, compareTarget);
  383. const handler = e => {
  384. if (guardEvent(e)) {
  385. if (this.replace) {
  386. router.replace(location);
  387. } else {
  388. router.push(location);
  389. }
  390. }
  391. };
  392. const on = { click: guardEvent };
  393. if (Array.isArray(this.event)) {
  394. this.event.forEach(e => { on[e] = handler; });
  395. } else {
  396. on[this.event] = handler;
  397. }
  398. const data = {
  399. class: classes
  400. };
  401. if (this.tag === 'a') {
  402. data.on = on;
  403. data.attrs = { href };
  404. } else {
  405. // find the first <a> child and apply listener and href
  406. const a = findAnchor(this.$slots.default);
  407. if (a) {
  408. // in case the <a> is a static node
  409. a.isStatic = false;
  410. const aData = a.data = extend({}, a.data);
  411. aData.on = on;
  412. const aAttrs = a.data.attrs = extend({}, a.data.attrs);
  413. aAttrs.href = href;
  414. } else {
  415. // doesn't have <a> child, apply listener to self
  416. data.on = on;
  417. }
  418. }
  419. return h(this.tag, data, this.$slots.default)
  420. }
  421. }
  422. function guardEvent (e) {
  423. // don't redirect with control keys
  424. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return
  425. // don't redirect when preventDefault called
  426. if (e.defaultPrevented) return
  427. // don't redirect on right click
  428. if (e.button !== undefined && e.button !== 0) return
  429. // don't redirect if `target="_blank"`
  430. if (e.currentTarget && e.currentTarget.getAttribute) {
  431. const target = e.currentTarget.getAttribute('target');
  432. if (/\b_blank\b/i.test(target)) return
  433. }
  434. // this may be a Weex event which doesn't have this method
  435. if (e.preventDefault) {
  436. e.preventDefault();
  437. }
  438. return true
  439. }
  440. function findAnchor (children) {
  441. if (children) {
  442. let child;
  443. for (let i = 0; i < children.length; i++) {
  444. child = children[i];
  445. if (child.tag === 'a') {
  446. return child
  447. }
  448. if (child.children && (child = findAnchor(child.children))) {
  449. return child
  450. }
  451. }
  452. }
  453. }
  454. let _Vue;
  455. function install (Vue) {
  456. if (install.installed && _Vue === Vue) return
  457. install.installed = true;
  458. _Vue = Vue;
  459. const isDef = v => v !== undefined;
  460. const registerInstance = (vm, callVal) => {
  461. let i = vm.$options._parentVnode;
  462. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  463. i(vm, callVal);
  464. }
  465. };
  466. Vue.mixin({
  467. beforeCreate () {
  468. if (isDef(this.$options.router)) {
  469. this._routerRoot = this;
  470. this._router = this.$options.router;
  471. this._router.init(this);
  472. Vue.util.defineReactive(this, '_route', this._router.history.current);
  473. } else {
  474. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  475. }
  476. registerInstance(this, this);
  477. },
  478. destroyed () {
  479. registerInstance(this);
  480. }
  481. });
  482. Object.defineProperty(Vue.prototype, '$router', {
  483. get () { return this._routerRoot._router }
  484. });
  485. Object.defineProperty(Vue.prototype, '$route', {
  486. get () { return this._routerRoot._route }
  487. });
  488. Vue.component('RouterView', View);
  489. Vue.component('RouterLink', Link);
  490. const strats = Vue.config.optionMergeStrategies;
  491. // use the same hook merging strategy for route hooks
  492. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  493. }
  494. /* */
  495. const inBrowser = typeof window !== 'undefined';
  496. /* */
  497. function resolvePath (
  498. relative,
  499. base,
  500. append
  501. ) {
  502. const firstChar = relative.charAt(0);
  503. if (firstChar === '/') {
  504. return relative
  505. }
  506. if (firstChar === '?' || firstChar === '#') {
  507. return base + relative
  508. }
  509. const stack = base.split('/');
  510. // remove trailing segment if:
  511. // - not appending
  512. // - appending to trailing slash (last segment is empty)
  513. if (!append || !stack[stack.length - 1]) {
  514. stack.pop();
  515. }
  516. // resolve relative path
  517. const segments = relative.replace(/^\//, '').split('/');
  518. for (let i = 0; i < segments.length; i++) {
  519. const segment = segments[i];
  520. if (segment === '..') {
  521. stack.pop();
  522. } else if (segment !== '.') {
  523. stack.push(segment);
  524. }
  525. }
  526. // ensure leading slash
  527. if (stack[0] !== '') {
  528. stack.unshift('');
  529. }
  530. return stack.join('/')
  531. }
  532. function parsePath (path) {
  533. let hash = '';
  534. let query = '';
  535. const hashIndex = path.indexOf('#');
  536. if (hashIndex >= 0) {
  537. hash = path.slice(hashIndex);
  538. path = path.slice(0, hashIndex);
  539. }
  540. const queryIndex = path.indexOf('?');
  541. if (queryIndex >= 0) {
  542. query = path.slice(queryIndex + 1);
  543. path = path.slice(0, queryIndex);
  544. }
  545. return {
  546. path,
  547. query,
  548. hash
  549. }
  550. }
  551. function cleanPath (path) {
  552. return path.replace(/\/\//g, '/')
  553. }
  554. var isarray = Array.isArray || function (arr) {
  555. return Object.prototype.toString.call(arr) == '[object Array]';
  556. };
  557. /**
  558. * Expose `pathToRegexp`.
  559. */
  560. var pathToRegexp_1 = pathToRegexp;
  561. var parse_1 = parse;
  562. var compile_1 = compile;
  563. var tokensToFunction_1 = tokensToFunction;
  564. var tokensToRegExp_1 = tokensToRegExp;
  565. /**
  566. * The main path matching regexp utility.
  567. *
  568. * @type {RegExp}
  569. */
  570. var PATH_REGEXP = new RegExp([
  571. // Match escaped characters that would otherwise appear in future matches.
  572. // This allows the user to escape special characters that won't transform.
  573. '(\\\\.)',
  574. // Match Express-style parameters and un-named parameters with a prefix
  575. // and optional suffixes. Matches appear as:
  576. //
  577. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  578. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  579. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  580. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  581. ].join('|'), 'g');
  582. /**
  583. * Parse a string for the raw tokens.
  584. *
  585. * @param {string} str
  586. * @param {Object=} options
  587. * @return {!Array}
  588. */
  589. function parse (str, options) {
  590. var tokens = [];
  591. var key = 0;
  592. var index = 0;
  593. var path = '';
  594. var defaultDelimiter = options && options.delimiter || '/';
  595. var res;
  596. while ((res = PATH_REGEXP.exec(str)) != null) {
  597. var m = res[0];
  598. var escaped = res[1];
  599. var offset = res.index;
  600. path += str.slice(index, offset);
  601. index = offset + m.length;
  602. // Ignore already escaped sequences.
  603. if (escaped) {
  604. path += escaped[1];
  605. continue
  606. }
  607. var next = str[index];
  608. var prefix = res[2];
  609. var name = res[3];
  610. var capture = res[4];
  611. var group = res[5];
  612. var modifier = res[6];
  613. var asterisk = res[7];
  614. // Push the current path onto the tokens.
  615. if (path) {
  616. tokens.push(path);
  617. path = '';
  618. }
  619. var partial = prefix != null && next != null && next !== prefix;
  620. var repeat = modifier === '+' || modifier === '*';
  621. var optional = modifier === '?' || modifier === '*';
  622. var delimiter = res[2] || defaultDelimiter;
  623. var pattern = capture || group;
  624. tokens.push({
  625. name: name || key++,
  626. prefix: prefix || '',
  627. delimiter: delimiter,
  628. optional: optional,
  629. repeat: repeat,
  630. partial: partial,
  631. asterisk: !!asterisk,
  632. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  633. });
  634. }
  635. // Match any characters still remaining.
  636. if (index < str.length) {
  637. path += str.substr(index);
  638. }
  639. // If the path exists, push it onto the end.
  640. if (path) {
  641. tokens.push(path);
  642. }
  643. return tokens
  644. }
  645. /**
  646. * Compile a string to a template function for the path.
  647. *
  648. * @param {string} str
  649. * @param {Object=} options
  650. * @return {!function(Object=, Object=)}
  651. */
  652. function compile (str, options) {
  653. return tokensToFunction(parse(str, options))
  654. }
  655. /**
  656. * Prettier encoding of URI path segments.
  657. *
  658. * @param {string}
  659. * @return {string}
  660. */
  661. function encodeURIComponentPretty (str) {
  662. return encodeURI(str).replace(/[\/?#]/g, function (c) {
  663. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  664. })
  665. }
  666. /**
  667. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  668. *
  669. * @param {string}
  670. * @return {string}
  671. */
  672. function encodeAsterisk (str) {
  673. return encodeURI(str).replace(/[?#]/g, function (c) {
  674. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  675. })
  676. }
  677. /**
  678. * Expose a method for transforming tokens into the path function.
  679. */
  680. function tokensToFunction (tokens) {
  681. // Compile all the tokens into regexps.
  682. var matches = new Array(tokens.length);
  683. // Compile all the patterns before compilation.
  684. for (var i = 0; i < tokens.length; i++) {
  685. if (typeof tokens[i] === 'object') {
  686. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
  687. }
  688. }
  689. return function (obj, opts) {
  690. var path = '';
  691. var data = obj || {};
  692. var options = opts || {};
  693. var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
  694. for (var i = 0; i < tokens.length; i++) {
  695. var token = tokens[i];
  696. if (typeof token === 'string') {
  697. path += token;
  698. continue
  699. }
  700. var value = data[token.name];
  701. var segment;
  702. if (value == null) {
  703. if (token.optional) {
  704. // Prepend partial segment prefixes.
  705. if (token.partial) {
  706. path += token.prefix;
  707. }
  708. continue
  709. } else {
  710. throw new TypeError('Expected "' + token.name + '" to be defined')
  711. }
  712. }
  713. if (isarray(value)) {
  714. if (!token.repeat) {
  715. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  716. }
  717. if (value.length === 0) {
  718. if (token.optional) {
  719. continue
  720. } else {
  721. throw new TypeError('Expected "' + token.name + '" to not be empty')
  722. }
  723. }
  724. for (var j = 0; j < value.length; j++) {
  725. segment = encode(value[j]);
  726. if (!matches[i].test(segment)) {
  727. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  728. }
  729. path += (j === 0 ? token.prefix : token.delimiter) + segment;
  730. }
  731. continue
  732. }
  733. segment = token.asterisk ? encodeAsterisk(value) : encode(value);
  734. if (!matches[i].test(segment)) {
  735. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  736. }
  737. path += token.prefix + segment;
  738. }
  739. return path
  740. }
  741. }
  742. /**
  743. * Escape a regular expression string.
  744. *
  745. * @param {string} str
  746. * @return {string}
  747. */
  748. function escapeString (str) {
  749. return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
  750. }
  751. /**
  752. * Escape the capturing group by escaping special characters and meaning.
  753. *
  754. * @param {string} group
  755. * @return {string}
  756. */
  757. function escapeGroup (group) {
  758. return group.replace(/([=!:$\/()])/g, '\\$1')
  759. }
  760. /**
  761. * Attach the keys as a property of the regexp.
  762. *
  763. * @param {!RegExp} re
  764. * @param {Array} keys
  765. * @return {!RegExp}
  766. */
  767. function attachKeys (re, keys) {
  768. re.keys = keys;
  769. return re
  770. }
  771. /**
  772. * Get the flags for a regexp from the options.
  773. *
  774. * @param {Object} options
  775. * @return {string}
  776. */
  777. function flags (options) {
  778. return options.sensitive ? '' : 'i'
  779. }
  780. /**
  781. * Pull out keys from a regexp.
  782. *
  783. * @param {!RegExp} path
  784. * @param {!Array} keys
  785. * @return {!RegExp}
  786. */
  787. function regexpToRegexp (path, keys) {
  788. // Use a negative lookahead to match only capturing groups.
  789. var groups = path.source.match(/\((?!\?)/g);
  790. if (groups) {
  791. for (var i = 0; i < groups.length; i++) {
  792. keys.push({
  793. name: i,
  794. prefix: null,
  795. delimiter: null,
  796. optional: false,
  797. repeat: false,
  798. partial: false,
  799. asterisk: false,
  800. pattern: null
  801. });
  802. }
  803. }
  804. return attachKeys(path, keys)
  805. }
  806. /**
  807. * Transform an array into a regexp.
  808. *
  809. * @param {!Array} path
  810. * @param {Array} keys
  811. * @param {!Object} options
  812. * @return {!RegExp}
  813. */
  814. function arrayToRegexp (path, keys, options) {
  815. var parts = [];
  816. for (var i = 0; i < path.length; i++) {
  817. parts.push(pathToRegexp(path[i], keys, options).source);
  818. }
  819. var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  820. return attachKeys(regexp, keys)
  821. }
  822. /**
  823. * Create a path regexp from string input.
  824. *
  825. * @param {string} path
  826. * @param {!Array} keys
  827. * @param {!Object} options
  828. * @return {!RegExp}
  829. */
  830. function stringToRegexp (path, keys, options) {
  831. return tokensToRegExp(parse(path, options), keys, options)
  832. }
  833. /**
  834. * Expose a function for taking tokens and returning a RegExp.
  835. *
  836. * @param {!Array} tokens
  837. * @param {(Array|Object)=} keys
  838. * @param {Object=} options
  839. * @return {!RegExp}
  840. */
  841. function tokensToRegExp (tokens, keys, options) {
  842. if (!isarray(keys)) {
  843. options = /** @type {!Object} */ (keys || options);
  844. keys = [];
  845. }
  846. options = options || {};
  847. var strict = options.strict;
  848. var end = options.end !== false;
  849. var route = '';
  850. // Iterate over the tokens and create our regexp string.
  851. for (var i = 0; i < tokens.length; i++) {
  852. var token = tokens[i];
  853. if (typeof token === 'string') {
  854. route += escapeString(token);
  855. } else {
  856. var prefix = escapeString(token.prefix);
  857. var capture = '(?:' + token.pattern + ')';
  858. keys.push(token);
  859. if (token.repeat) {
  860. capture += '(?:' + prefix + capture + ')*';
  861. }
  862. if (token.optional) {
  863. if (!token.partial) {
  864. capture = '(?:' + prefix + '(' + capture + '))?';
  865. } else {
  866. capture = prefix + '(' + capture + ')?';
  867. }
  868. } else {
  869. capture = prefix + '(' + capture + ')';
  870. }
  871. route += capture;
  872. }
  873. }
  874. var delimiter = escapeString(options.delimiter || '/');
  875. var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  876. // In non-strict mode we allow a slash at the end of match. If the path to
  877. // match already ends with a slash, we remove it for consistency. The slash
  878. // is valid at the end of a path match, not in the middle. This is important
  879. // in non-ending mode, where "/test/" shouldn't match "/test//route".
  880. if (!strict) {
  881. route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  882. }
  883. if (end) {
  884. route += '$';
  885. } else {
  886. // In non-ending mode, we need the capturing groups to match as much as
  887. // possible by using a positive lookahead to the end or next path segment.
  888. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  889. }
  890. return attachKeys(new RegExp('^' + route, flags(options)), keys)
  891. }
  892. /**
  893. * Normalize the given path string, returning a regular expression.
  894. *
  895. * An empty array can be passed in for the keys, which will hold the
  896. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  897. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  898. *
  899. * @param {(string|RegExp|Array)} path
  900. * @param {(Array|Object)=} keys
  901. * @param {Object=} options
  902. * @return {!RegExp}
  903. */
  904. function pathToRegexp (path, keys, options) {
  905. if (!isarray(keys)) {
  906. options = /** @type {!Object} */ (keys || options);
  907. keys = [];
  908. }
  909. options = options || {};
  910. if (path instanceof RegExp) {
  911. return regexpToRegexp(path, /** @type {!Array} */ (keys))
  912. }
  913. if (isarray(path)) {
  914. return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
  915. }
  916. return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
  917. }
  918. pathToRegexp_1.parse = parse_1;
  919. pathToRegexp_1.compile = compile_1;
  920. pathToRegexp_1.tokensToFunction = tokensToFunction_1;
  921. pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
  922. /* */
  923. // $flow-disable-line
  924. const regexpCompileCache = Object.create(null);
  925. function fillParams (
  926. path,
  927. params,
  928. routeMsg
  929. ) {
  930. params = params || {};
  931. try {
  932. const filler =
  933. regexpCompileCache[path] ||
  934. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  935. // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
  936. if (params.pathMatch) params[0] = params.pathMatch;
  937. return filler(params, { pretty: true })
  938. } catch (e) {
  939. {
  940. warn(false, `missing param for ${routeMsg}: ${e.message}`);
  941. }
  942. return ''
  943. } finally {
  944. // delete the 0 if it was added
  945. delete params[0];
  946. }
  947. }
  948. /* */
  949. function createRouteMap (
  950. routes,
  951. oldPathList,
  952. oldPathMap,
  953. oldNameMap
  954. ) {
  955. // the path list is used to control path matching priority
  956. const pathList = oldPathList || [];
  957. // $flow-disable-line
  958. const pathMap = oldPathMap || Object.create(null);
  959. // $flow-disable-line
  960. const nameMap = oldNameMap || Object.create(null);
  961. routes.forEach(route => {
  962. addRouteRecord(pathList, pathMap, nameMap, route);
  963. });
  964. // ensure wildcard routes are always at the end
  965. for (let i = 0, l = pathList.length; i < l; i++) {
  966. if (pathList[i] === '*') {
  967. pathList.push(pathList.splice(i, 1)[0]);
  968. l--;
  969. i--;
  970. }
  971. }
  972. return {
  973. pathList,
  974. pathMap,
  975. nameMap
  976. }
  977. }
  978. function addRouteRecord (
  979. pathList,
  980. pathMap,
  981. nameMap,
  982. route,
  983. parent,
  984. matchAs
  985. ) {
  986. const { path, name } = route;
  987. {
  988. assert(path != null, `"path" is required in a route configuration.`);
  989. assert(
  990. typeof route.component !== 'string',
  991. `route config "component" for path: ${String(path || name)} cannot be a ` +
  992. `string id. Use an actual component instead.`
  993. );
  994. }
  995. const pathToRegexpOptions = route.pathToRegexpOptions || {};
  996. const normalizedPath = normalizePath(
  997. path,
  998. parent,
  999. pathToRegexpOptions.strict
  1000. );
  1001. if (typeof route.caseSensitive === 'boolean') {
  1002. pathToRegexpOptions.sensitive = route.caseSensitive;
  1003. }
  1004. const record = {
  1005. path: normalizedPath,
  1006. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1007. components: route.components || { default: route.component },
  1008. instances: {},
  1009. name,
  1010. parent,
  1011. matchAs,
  1012. redirect: route.redirect,
  1013. beforeEnter: route.beforeEnter,
  1014. meta: route.meta || {},
  1015. props: route.props == null
  1016. ? {}
  1017. : route.components
  1018. ? route.props
  1019. : { default: route.props }
  1020. };
  1021. if (route.children) {
  1022. // Warn if route is named, does not redirect and has a default child route.
  1023. // If users navigate to this route by name, the default child will
  1024. // not be rendered (GH Issue #629)
  1025. {
  1026. if (route.name && !route.redirect && route.children.some(child => /^\/?$/.test(child.path))) {
  1027. warn(
  1028. false,
  1029. `Named Route '${route.name}' has a default child route. ` +
  1030. `When navigating to this named route (:to="{name: '${route.name}'"), ` +
  1031. `the default child route will not be rendered. Remove the name from ` +
  1032. `this route and use the name of the default child route for named ` +
  1033. `links instead.`
  1034. );
  1035. }
  1036. }
  1037. route.children.forEach(child => {
  1038. const childMatchAs = matchAs
  1039. ? cleanPath(`${matchAs}/${child.path}`)
  1040. : undefined;
  1041. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1042. });
  1043. }
  1044. if (route.alias !== undefined) {
  1045. const aliases = Array.isArray(route.alias)
  1046. ? route.alias
  1047. : [route.alias];
  1048. aliases.forEach(alias => {
  1049. const aliasRoute = {
  1050. path: alias,
  1051. children: route.children
  1052. };
  1053. addRouteRecord(
  1054. pathList,
  1055. pathMap,
  1056. nameMap,
  1057. aliasRoute,
  1058. parent,
  1059. record.path || '/' // matchAs
  1060. );
  1061. });
  1062. }
  1063. if (!pathMap[record.path]) {
  1064. pathList.push(record.path);
  1065. pathMap[record.path] = record;
  1066. }
  1067. if (name) {
  1068. if (!nameMap[name]) {
  1069. nameMap[name] = record;
  1070. } else if ("development" !== 'production' && !matchAs) {
  1071. warn(
  1072. false,
  1073. `Duplicate named routes definition: ` +
  1074. `{ name: "${name}", path: "${record.path}" }`
  1075. );
  1076. }
  1077. }
  1078. }
  1079. function compileRouteRegex (path, pathToRegexpOptions) {
  1080. const regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1081. {
  1082. const keys = Object.create(null);
  1083. regex.keys.forEach(key => {
  1084. warn(!keys[key.name], `Duplicate param keys in route with path: "${path}"`);
  1085. keys[key.name] = true;
  1086. });
  1087. }
  1088. return regex
  1089. }
  1090. function normalizePath (path, parent, strict) {
  1091. if (!strict) path = path.replace(/\/$/, '');
  1092. if (path[0] === '/') return path
  1093. if (parent == null) return path
  1094. return cleanPath(`${parent.path}/${path}`)
  1095. }
  1096. /* */
  1097. function normalizeLocation (
  1098. raw,
  1099. current,
  1100. append,
  1101. router
  1102. ) {
  1103. let next = typeof raw === 'string' ? { path: raw } : raw;
  1104. // named target
  1105. if (next._normalized) {
  1106. return next
  1107. } else if (next.name) {
  1108. return extend({}, raw)
  1109. }
  1110. // relative params
  1111. if (!next.path && next.params && current) {
  1112. next = extend({}, next);
  1113. next._normalized = true;
  1114. const params = extend(extend({}, current.params), next.params);
  1115. if (current.name) {
  1116. next.name = current.name;
  1117. next.params = params;
  1118. } else if (current.matched.length) {
  1119. const rawPath = current.matched[current.matched.length - 1].path;
  1120. next.path = fillParams(rawPath, params, `path ${current.path}`);
  1121. } else {
  1122. warn(false, `relative params navigation requires a current route.`);
  1123. }
  1124. return next
  1125. }
  1126. const parsedPath = parsePath(next.path || '');
  1127. const basePath = (current && current.path) || '/';
  1128. const path = parsedPath.path
  1129. ? resolvePath(parsedPath.path, basePath, append || next.append)
  1130. : basePath;
  1131. const query = resolveQuery(
  1132. parsedPath.query,
  1133. next.query,
  1134. router && router.options.parseQuery
  1135. );
  1136. let hash = next.hash || parsedPath.hash;
  1137. if (hash && hash.charAt(0) !== '#') {
  1138. hash = `#${hash}`;
  1139. }
  1140. return {
  1141. _normalized: true,
  1142. path,
  1143. query,
  1144. hash
  1145. }
  1146. }
  1147. /* */
  1148. function createMatcher (
  1149. routes,
  1150. router
  1151. ) {
  1152. const { pathList, pathMap, nameMap } = createRouteMap(routes);
  1153. function addRoutes (routes) {
  1154. createRouteMap(routes, pathList, pathMap, nameMap);
  1155. }
  1156. function match (
  1157. raw,
  1158. currentRoute,
  1159. redirectedFrom
  1160. ) {
  1161. const location = normalizeLocation(raw, currentRoute, false, router);
  1162. const { name } = location;
  1163. if (name) {
  1164. const record = nameMap[name];
  1165. {
  1166. warn(record, `Route with name '${name}' does not exist`);
  1167. }
  1168. if (!record) return _createRoute(null, location)
  1169. const paramNames = record.regex.keys
  1170. .filter(key => !key.optional)
  1171. .map(key => key.name);
  1172. if (typeof location.params !== 'object') {
  1173. location.params = {};
  1174. }
  1175. if (currentRoute && typeof currentRoute.params === 'object') {
  1176. for (const key in currentRoute.params) {
  1177. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1178. location.params[key] = currentRoute.params[key];
  1179. }
  1180. }
  1181. }
  1182. if (record) {
  1183. location.path = fillParams(record.path, location.params, `named route "${name}"`);
  1184. return _createRoute(record, location, redirectedFrom)
  1185. }
  1186. } else if (location.path) {
  1187. location.params = {};
  1188. for (let i = 0; i < pathList.length; i++) {
  1189. const path = pathList[i];
  1190. const record = pathMap[path];
  1191. if (matchRoute(record.regex, location.path, location.params)) {
  1192. return _createRoute(record, location, redirectedFrom)
  1193. }
  1194. }
  1195. }
  1196. // no match
  1197. return _createRoute(null, location)
  1198. }
  1199. function redirect (
  1200. record,
  1201. location
  1202. ) {
  1203. const originalRedirect = record.redirect;
  1204. let redirect = typeof originalRedirect === 'function'
  1205. ? originalRedirect(createRoute(record, location, null, router))
  1206. : originalRedirect;
  1207. if (typeof redirect === 'string') {
  1208. redirect = { path: redirect };
  1209. }
  1210. if (!redirect || typeof redirect !== 'object') {
  1211. {
  1212. warn(
  1213. false, `invalid redirect option: ${JSON.stringify(redirect)}`
  1214. );
  1215. }
  1216. return _createRoute(null, location)
  1217. }
  1218. const re = redirect;
  1219. const { name, path } = re;
  1220. let { query, hash, params } = location;
  1221. query = re.hasOwnProperty('query') ? re.query : query;
  1222. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1223. params = re.hasOwnProperty('params') ? re.params : params;
  1224. if (name) {
  1225. // resolved named direct
  1226. const targetRecord = nameMap[name];
  1227. {
  1228. assert(targetRecord, `redirect failed: named route "${name}" not found.`);
  1229. }
  1230. return match({
  1231. _normalized: true,
  1232. name,
  1233. query,
  1234. hash,
  1235. params
  1236. }, undefined, location)
  1237. } else if (path) {
  1238. // 1. resolve relative redirect
  1239. const rawPath = resolveRecordPath(path, record);
  1240. // 2. resolve params
  1241. const resolvedPath = fillParams(rawPath, params, `redirect route with path "${rawPath}"`);
  1242. // 3. rematch with existing query and hash
  1243. return match({
  1244. _normalized: true,
  1245. path: resolvedPath,
  1246. query,
  1247. hash
  1248. }, undefined, location)
  1249. } else {
  1250. {
  1251. warn(false, `invalid redirect option: ${JSON.stringify(redirect)}`);
  1252. }
  1253. return _createRoute(null, location)
  1254. }
  1255. }
  1256. function alias (
  1257. record,
  1258. location,
  1259. matchAs
  1260. ) {
  1261. const aliasedPath = fillParams(matchAs, location.params, `aliased route with path "${matchAs}"`);
  1262. const aliasedMatch = match({
  1263. _normalized: true,
  1264. path: aliasedPath
  1265. });
  1266. if (aliasedMatch) {
  1267. const matched = aliasedMatch.matched;
  1268. const aliasedRecord = matched[matched.length - 1];
  1269. location.params = aliasedMatch.params;
  1270. return _createRoute(aliasedRecord, location)
  1271. }
  1272. return _createRoute(null, location)
  1273. }
  1274. function _createRoute (
  1275. record,
  1276. location,
  1277. redirectedFrom
  1278. ) {
  1279. if (record && record.redirect) {
  1280. return redirect(record, redirectedFrom || location)
  1281. }
  1282. if (record && record.matchAs) {
  1283. return alias(record, location, record.matchAs)
  1284. }
  1285. return createRoute(record, location, redirectedFrom, router)
  1286. }
  1287. return {
  1288. match,
  1289. addRoutes
  1290. }
  1291. }
  1292. function matchRoute (
  1293. regex,
  1294. path,
  1295. params
  1296. ) {
  1297. const m = path.match(regex);
  1298. if (!m) {
  1299. return false
  1300. } else if (!params) {
  1301. return true
  1302. }
  1303. for (let i = 1, len = m.length; i < len; ++i) {
  1304. const key = regex.keys[i - 1];
  1305. const val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
  1306. if (key) {
  1307. // Fix #1994: using * with props: true generates a param named 0
  1308. params[key.name || 'pathMatch'] = val;
  1309. }
  1310. }
  1311. return true
  1312. }
  1313. function resolveRecordPath (path, record) {
  1314. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1315. }
  1316. /* */
  1317. const positionStore = Object.create(null);
  1318. function setupScroll () {
  1319. // Fix for #1585 for Firefox
  1320. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1321. window.history.replaceState({ key: getStateKey() }, '', window.location.href.replace(window.location.origin, ''));
  1322. window.addEventListener('popstate', e => {
  1323. saveScrollPosition();
  1324. if (e.state && e.state.key) {
  1325. setStateKey(e.state.key);
  1326. }
  1327. });
  1328. }
  1329. function handleScroll (
  1330. router,
  1331. to,
  1332. from,
  1333. isPop
  1334. ) {
  1335. if (!router.app) {
  1336. return
  1337. }
  1338. const behavior = router.options.scrollBehavior;
  1339. if (!behavior) {
  1340. return
  1341. }
  1342. {
  1343. assert(typeof behavior === 'function', `scrollBehavior must be a function`);
  1344. }
  1345. // wait until re-render finishes before scrolling
  1346. router.app.$nextTick(() => {
  1347. const position = getScrollPosition();
  1348. const shouldScroll = behavior.call(router, to, from, isPop ? position : null);
  1349. if (!shouldScroll) {
  1350. return
  1351. }
  1352. if (typeof shouldScroll.then === 'function') {
  1353. shouldScroll.then(shouldScroll => {
  1354. scrollToPosition((shouldScroll), position);
  1355. }).catch(err => {
  1356. {
  1357. assert(false, err.toString());
  1358. }
  1359. });
  1360. } else {
  1361. scrollToPosition(shouldScroll, position);
  1362. }
  1363. });
  1364. }
  1365. function saveScrollPosition () {
  1366. const key = getStateKey();
  1367. if (key) {
  1368. positionStore[key] = {
  1369. x: window.pageXOffset,
  1370. y: window.pageYOffset
  1371. };
  1372. }
  1373. }
  1374. function getScrollPosition () {
  1375. const key = getStateKey();
  1376. if (key) {
  1377. return positionStore[key]
  1378. }
  1379. }
  1380. function getElementPosition (el, offset) {
  1381. const docEl = document.documentElement;
  1382. const docRect = docEl.getBoundingClientRect();
  1383. const elRect = el.getBoundingClientRect();
  1384. return {
  1385. x: elRect.left - docRect.left - offset.x,
  1386. y: elRect.top - docRect.top - offset.y
  1387. }
  1388. }
  1389. function isValidPosition (obj) {
  1390. return isNumber(obj.x) || isNumber(obj.y)
  1391. }
  1392. function normalizePosition (obj) {
  1393. return {
  1394. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1395. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1396. }
  1397. }
  1398. function normalizeOffset (obj) {
  1399. return {
  1400. x: isNumber(obj.x) ? obj.x : 0,
  1401. y: isNumber(obj.y) ? obj.y : 0
  1402. }
  1403. }
  1404. function isNumber (v) {
  1405. return typeof v === 'number'
  1406. }
  1407. function scrollToPosition (shouldScroll, position) {
  1408. const isObject = typeof shouldScroll === 'object';
  1409. if (isObject && typeof shouldScroll.selector === 'string') {
  1410. const el = document.querySelector(shouldScroll.selector);
  1411. if (el) {
  1412. let offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {};
  1413. offset = normalizeOffset(offset);
  1414. position = getElementPosition(el, offset);
  1415. } else if (isValidPosition(shouldScroll)) {
  1416. position = normalizePosition(shouldScroll);
  1417. }
  1418. } else if (isObject && isValidPosition(shouldScroll)) {
  1419. position = normalizePosition(shouldScroll);
  1420. }
  1421. if (position) {
  1422. window.scrollTo(position.x, position.y);
  1423. }
  1424. }
  1425. /* */
  1426. const supportsPushState = inBrowser && (function () {
  1427. const ua = window.navigator.userAgent;
  1428. if (
  1429. (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
  1430. ua.indexOf('Mobile Safari') !== -1 &&
  1431. ua.indexOf('Chrome') === -1 &&
  1432. ua.indexOf('Windows Phone') === -1
  1433. ) {
  1434. return false
  1435. }
  1436. return window.history && 'pushState' in window.history
  1437. })();
  1438. // use User Timing api (if present) for more accurate key precision
  1439. const Time = inBrowser && window.performance && window.performance.now
  1440. ? window.performance
  1441. : Date;
  1442. let _key = genKey();
  1443. function genKey () {
  1444. return Time.now().toFixed(3)
  1445. }
  1446. function getStateKey () {
  1447. return _key
  1448. }
  1449. function setStateKey (key) {
  1450. _key = key;
  1451. }
  1452. function pushState (url, replace) {
  1453. saveScrollPosition();
  1454. // try...catch the pushState call to get around Safari
  1455. // DOM Exception 18 where it limits to 100 pushState calls
  1456. const history = window.history;
  1457. try {
  1458. if (replace) {
  1459. history.replaceState({ key: _key }, '', url);
  1460. } else {
  1461. _key = genKey();
  1462. history.pushState({ key: _key }, '', url);
  1463. }
  1464. } catch (e) {
  1465. window.location[replace ? 'replace' : 'assign'](url);
  1466. }
  1467. }
  1468. function replaceState (url) {
  1469. pushState(url, true);
  1470. }
  1471. /* */
  1472. function runQueue (queue, fn, cb) {
  1473. const step = index => {
  1474. if (index >= queue.length) {
  1475. cb();
  1476. } else {
  1477. if (queue[index]) {
  1478. fn(queue[index], () => {
  1479. step(index + 1);
  1480. });
  1481. } else {
  1482. step(index + 1);
  1483. }
  1484. }
  1485. };
  1486. step(0);
  1487. }
  1488. /* */
  1489. function resolveAsyncComponents (matched) {
  1490. return (to, from, next) => {
  1491. let hasAsync = false;
  1492. let pending = 0;
  1493. let error = null;
  1494. flatMapComponents(matched, (def, _, match, key) => {
  1495. // if it's a function and doesn't have cid attached,
  1496. // assume it's an async component resolve function.
  1497. // we are not using Vue's default async resolving mechanism because
  1498. // we want to halt the navigation until the incoming component has been
  1499. // resolved.
  1500. if (typeof def === 'function' && def.cid === undefined) {
  1501. hasAsync = true;
  1502. pending++;
  1503. const resolve = once(resolvedDef => {
  1504. if (isESModule(resolvedDef)) {
  1505. resolvedDef = resolvedDef.default;
  1506. }
  1507. // save resolved on async factory in case it's used elsewhere
  1508. def.resolved = typeof resolvedDef === 'function'
  1509. ? resolvedDef
  1510. : _Vue.extend(resolvedDef);
  1511. match.components[key] = resolvedDef;
  1512. pending--;
  1513. if (pending <= 0) {
  1514. next();
  1515. }
  1516. });
  1517. const reject = once(reason => {
  1518. const msg = `Failed to resolve async component ${key}: ${reason}`;
  1519. "development" !== 'production' && warn(false, msg);
  1520. if (!error) {
  1521. error = isError(reason)
  1522. ? reason
  1523. : new Error(msg);
  1524. next(error);
  1525. }
  1526. });
  1527. let res;
  1528. try {
  1529. res = def(resolve, reject);
  1530. } catch (e) {
  1531. reject(e);
  1532. }
  1533. if (res) {
  1534. if (typeof res.then === 'function') {
  1535. res.then(resolve, reject);
  1536. } else {
  1537. // new syntax in Vue 2.3
  1538. const comp = res.component;
  1539. if (comp && typeof comp.then === 'function') {
  1540. comp.then(resolve, reject);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. });
  1546. if (!hasAsync) next();
  1547. }
  1548. }
  1549. function flatMapComponents (
  1550. matched,
  1551. fn
  1552. ) {
  1553. return flatten(matched.map(m => {
  1554. return Object.keys(m.components).map(key => fn(
  1555. m.components[key],
  1556. m.instances[key],
  1557. m, key
  1558. ))
  1559. }))
  1560. }
  1561. function flatten (arr) {
  1562. return Array.prototype.concat.apply([], arr)
  1563. }
  1564. const hasSymbol =
  1565. typeof Symbol === 'function' &&
  1566. typeof Symbol.toStringTag === 'symbol';
  1567. function isESModule (obj) {
  1568. return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  1569. }
  1570. // in Webpack 2, require.ensure now also returns a Promise
  1571. // so the resolve/reject functions may get called an extra time
  1572. // if the user uses an arrow function shorthand that happens to
  1573. // return that Promise.
  1574. function once (fn) {
  1575. let called = false;
  1576. return function (...args) {
  1577. if (called) return
  1578. called = true;
  1579. return fn.apply(this, args)
  1580. }
  1581. }
  1582. /* */
  1583. class History {
  1584. // implemented by sub-classes
  1585. constructor (router, base) {
  1586. this.router = router;
  1587. this.base = normalizeBase(base);
  1588. // start with a route object that stands for "nowhere"
  1589. this.current = START;
  1590. this.pending = null;
  1591. this.ready = false;
  1592. this.readyCbs = [];
  1593. this.readyErrorCbs = [];
  1594. this.errorCbs = [];
  1595. }
  1596. listen (cb) {
  1597. this.cb = cb;
  1598. }
  1599. onReady (cb, errorCb) {
  1600. if (this.ready) {
  1601. cb();
  1602. } else {
  1603. this.readyCbs.push(cb);
  1604. if (errorCb) {
  1605. this.readyErrorCbs.push(errorCb);
  1606. }
  1607. }
  1608. }
  1609. onError (errorCb) {
  1610. this.errorCbs.push(errorCb);
  1611. }
  1612. transitionTo (location, onComplete, onAbort) {
  1613. const route = this.router.match(location, this.current);
  1614. this.confirmTransition(route, () => {
  1615. this.updateRoute(route);
  1616. onComplete && onComplete(route);
  1617. this.ensureURL();
  1618. // fire ready cbs once
  1619. if (!this.ready) {
  1620. this.ready = true;
  1621. this.readyCbs.forEach(cb => { cb(route); });
  1622. }
  1623. }, err => {
  1624. if (onAbort) {
  1625. onAbort(err);
  1626. }
  1627. if (err && !this.ready) {
  1628. this.ready = true;
  1629. this.readyErrorCbs.forEach(cb => { cb(err); });
  1630. }
  1631. });
  1632. }
  1633. confirmTransition (route, onComplete, onAbort) {
  1634. const current = this.current;
  1635. const abort = err => {
  1636. if (isError(err)) {
  1637. if (this.errorCbs.length) {
  1638. this.errorCbs.forEach(cb => { cb(err); });
  1639. } else {
  1640. warn(false, 'uncaught error during route navigation:');
  1641. console.error(err);
  1642. }
  1643. }
  1644. onAbort && onAbort(err);
  1645. };
  1646. if (
  1647. isSameRoute(route, current) &&
  1648. // in the case the route map has been dynamically appended to
  1649. route.matched.length === current.matched.length
  1650. ) {
  1651. this.ensureURL();
  1652. return abort()
  1653. }
  1654. const {
  1655. updated,
  1656. deactivated,
  1657. activated
  1658. } = resolveQueue(this.current.matched, route.matched);
  1659. const queue = [].concat(
  1660. // in-component leave guards
  1661. extractLeaveGuards(deactivated),
  1662. // global before hooks
  1663. this.router.beforeHooks,
  1664. // in-component update hooks
  1665. extractUpdateHooks(updated),
  1666. // in-config enter guards
  1667. activated.map(m => m.beforeEnter),
  1668. // async components
  1669. resolveAsyncComponents(activated)
  1670. );
  1671. this.pending = route;
  1672. const iterator = (hook, next) => {
  1673. if (this.pending !== route) {
  1674. return abort()
  1675. }
  1676. try {
  1677. hook(route, current, (to) => {
  1678. if (to === false || isError(to)) {
  1679. // next(false) -> abort navigation, ensure current URL
  1680. this.ensureURL(true);
  1681. abort(to);
  1682. } else if (
  1683. typeof to === 'string' ||
  1684. (typeof to === 'object' && (
  1685. typeof to.path === 'string' ||
  1686. typeof to.name === 'string'
  1687. ))
  1688. ) {
  1689. // next('/') or next({ path: '/' }) -> redirect
  1690. abort();
  1691. if (typeof to === 'object' && to.replace) {
  1692. this.replace(to);
  1693. } else {
  1694. this.push(to);
  1695. }
  1696. } else {
  1697. // confirm transition and pass on the value
  1698. next(to);
  1699. }
  1700. });
  1701. } catch (e) {
  1702. abort(e);
  1703. }
  1704. };
  1705. runQueue(queue, iterator, () => {
  1706. const postEnterCbs = [];
  1707. const isValid = () => this.current === route;
  1708. // wait until async components are resolved before
  1709. // extracting in-component enter guards
  1710. const enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
  1711. const queue = enterGuards.concat(this.router.resolveHooks);
  1712. runQueue(queue, iterator, () => {
  1713. if (this.pending !== route) {
  1714. return abort()
  1715. }
  1716. this.pending = null;
  1717. onComplete(route);
  1718. if (this.router.app) {
  1719. this.router.app.$nextTick(() => {
  1720. postEnterCbs.forEach(cb => { cb(); });
  1721. });
  1722. }
  1723. });
  1724. });
  1725. }
  1726. updateRoute (route) {
  1727. const prev = this.current;
  1728. this.current = route;
  1729. this.cb && this.cb(route);
  1730. this.router.afterHooks.forEach(hook => {
  1731. hook && hook(route, prev);
  1732. });
  1733. }
  1734. }
  1735. function normalizeBase (base) {
  1736. if (!base) {
  1737. if (inBrowser) {
  1738. // respect <base> tag
  1739. const baseEl = document.querySelector('base');
  1740. base = (baseEl && baseEl.getAttribute('href')) || '/';
  1741. // strip full URL origin
  1742. base = base.replace(/^https?:\/\/[^\/]+/, '');
  1743. } else {
  1744. base = '/';
  1745. }
  1746. }
  1747. // make sure there's the starting slash
  1748. if (base.charAt(0) !== '/') {
  1749. base = '/' + base;
  1750. }
  1751. // remove trailing slash
  1752. return base.replace(/\/$/, '')
  1753. }
  1754. function resolveQueue (
  1755. current,
  1756. next
  1757. ) {
  1758. let i;
  1759. const max = Math.max(current.length, next.length);
  1760. for (i = 0; i < max; i++) {
  1761. if (current[i] !== next[i]) {
  1762. break
  1763. }
  1764. }
  1765. return {
  1766. updated: next.slice(0, i),
  1767. activated: next.slice(i),
  1768. deactivated: current.slice(i)
  1769. }
  1770. }
  1771. function extractGuards (
  1772. records,
  1773. name,
  1774. bind,
  1775. reverse
  1776. ) {
  1777. const guards = flatMapComponents(records, (def, instance, match, key) => {
  1778. const guard = extractGuard(def, name);
  1779. if (guard) {
  1780. return Array.isArray(guard)
  1781. ? guard.map(guard => bind(guard, instance, match, key))
  1782. : bind(guard, instance, match, key)
  1783. }
  1784. });
  1785. return flatten(reverse ? guards.reverse() : guards)
  1786. }
  1787. function extractGuard (
  1788. def,
  1789. key
  1790. ) {
  1791. if (typeof def !== 'function') {
  1792. // extend now so that global mixins are applied.
  1793. def = _Vue.extend(def);
  1794. }
  1795. return def.options[key]
  1796. }
  1797. function extractLeaveGuards (deactivated) {
  1798. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  1799. }
  1800. function extractUpdateHooks (updated) {
  1801. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  1802. }
  1803. function bindGuard (guard, instance) {
  1804. if (instance) {
  1805. return function boundRouteGuard () {
  1806. return guard.apply(instance, arguments)
  1807. }
  1808. }
  1809. }
  1810. function extractEnterGuards (
  1811. activated,
  1812. cbs,
  1813. isValid
  1814. ) {
  1815. return extractGuards(activated, 'beforeRouteEnter', (guard, _, match, key) => {
  1816. return bindEnterGuard(guard, match, key, cbs, isValid)
  1817. })
  1818. }
  1819. function bindEnterGuard (
  1820. guard,
  1821. match,
  1822. key,
  1823. cbs,
  1824. isValid
  1825. ) {
  1826. return function routeEnterGuard (to, from, next) {
  1827. return guard(to, from, cb => {
  1828. next(cb);
  1829. if (typeof cb === 'function') {
  1830. cbs.push(() => {
  1831. // #750
  1832. // if a router-view is wrapped with an out-in transition,
  1833. // the instance may not have been registered at this time.
  1834. // we will need to poll for registration until current route
  1835. // is no longer valid.
  1836. poll(cb, match.instances, key, isValid);
  1837. });
  1838. }
  1839. })
  1840. }
  1841. }
  1842. function poll (
  1843. cb, // somehow flow cannot infer this is a function
  1844. instances,
  1845. key,
  1846. isValid
  1847. ) {
  1848. if (
  1849. instances[key] &&
  1850. !instances[key]._isBeingDestroyed // do not reuse being destroyed instance
  1851. ) {
  1852. cb(instances[key]);
  1853. } else if (isValid()) {
  1854. setTimeout(() => {
  1855. poll(cb, instances, key, isValid);
  1856. }, 16);
  1857. }
  1858. }
  1859. /* */
  1860. class HTML5History extends History {
  1861. constructor (router, base) {
  1862. super(router, base);
  1863. const expectScroll = router.options.scrollBehavior;
  1864. const supportsScroll = supportsPushState && expectScroll;
  1865. if (supportsScroll) {
  1866. setupScroll();
  1867. }
  1868. const initLocation = getLocation(this.base);
  1869. window.addEventListener('popstate', e => {
  1870. const current = this.current;
  1871. // Avoiding first `popstate` event dispatched in some browsers but first
  1872. // history route not updated since async guard at the same time.
  1873. const location = getLocation(this.base);
  1874. if (this.current === START && location === initLocation) {
  1875. return
  1876. }
  1877. this.transitionTo(location, route => {
  1878. if (supportsScroll) {
  1879. handleScroll(router, route, current, true);
  1880. }
  1881. });
  1882. });
  1883. }
  1884. go (n) {
  1885. window.history.go(n);
  1886. }
  1887. push (location, onComplete, onAbort) {
  1888. const { current: fromRoute } = this;
  1889. this.transitionTo(location, route => {
  1890. pushState(cleanPath(this.base + route.fullPath));
  1891. handleScroll(this.router, route, fromRoute, false);
  1892. onComplete && onComplete(route);
  1893. }, onAbort);
  1894. }
  1895. replace (location, onComplete, onAbort) {
  1896. const { current: fromRoute } = this;
  1897. this.transitionTo(location, route => {
  1898. replaceState(cleanPath(this.base + route.fullPath));
  1899. handleScroll(this.router, route, fromRoute, false);
  1900. onComplete && onComplete(route);
  1901. }, onAbort);
  1902. }
  1903. ensureURL (push) {
  1904. if (getLocation(this.base) !== this.current.fullPath) {
  1905. const current = cleanPath(this.base + this.current.fullPath);
  1906. push ? pushState(current) : replaceState(current);
  1907. }
  1908. }
  1909. getCurrentLocation () {
  1910. return getLocation(this.base)
  1911. }
  1912. }
  1913. function getLocation (base) {
  1914. let path = decodeURI(window.location.pathname);
  1915. if (base && path.indexOf(base) === 0) {
  1916. path = path.slice(base.length);
  1917. }
  1918. return (path || '/') + window.location.search + window.location.hash
  1919. }
  1920. /* */
  1921. class HashHistory extends History {
  1922. constructor (router, base, fallback) {
  1923. super(router, base);
  1924. // check history fallback deeplinking
  1925. if (fallback && checkFallback(this.base)) {
  1926. return
  1927. }
  1928. ensureSlash();
  1929. }
  1930. // this is delayed until the app mounts
  1931. // to avoid the hashchange listener being fired too early
  1932. setupListeners () {
  1933. const router = this.router;
  1934. const expectScroll = router.options.scrollBehavior;
  1935. const supportsScroll = supportsPushState && expectScroll;
  1936. if (supportsScroll) {
  1937. setupScroll();
  1938. }
  1939. window.addEventListener(supportsPushState ? 'popstate' : 'hashchange', () => {
  1940. const current = this.current;
  1941. if (!ensureSlash()) {
  1942. return
  1943. }
  1944. this.transitionTo(getHash(), route => {
  1945. if (supportsScroll) {
  1946. handleScroll(this.router, route, current, true);
  1947. }
  1948. if (!supportsPushState) {
  1949. replaceHash(route.fullPath);
  1950. }
  1951. });
  1952. });
  1953. }
  1954. push (location, onComplete, onAbort) {
  1955. const { current: fromRoute } = this;
  1956. this.transitionTo(location, route => {
  1957. pushHash(route.fullPath);
  1958. handleScroll(this.router, route, fromRoute, false);
  1959. onComplete && onComplete(route);
  1960. }, onAbort);
  1961. }
  1962. replace (location, onComplete, onAbort) {
  1963. const { current: fromRoute } = this;
  1964. this.transitionTo(location, route => {
  1965. replaceHash(route.fullPath);
  1966. handleScroll(this.router, route, fromRoute, false);
  1967. onComplete && onComplete(route);
  1968. }, onAbort);
  1969. }
  1970. go (n) {
  1971. window.history.go(n);
  1972. }
  1973. ensureURL (push) {
  1974. const current = this.current.fullPath;
  1975. if (getHash() !== current) {
  1976. push ? pushHash(current) : replaceHash(current);
  1977. }
  1978. }
  1979. getCurrentLocation () {
  1980. return getHash()
  1981. }
  1982. }
  1983. function checkFallback (base) {
  1984. const location = getLocation(base);
  1985. if (!/^\/#/.test(location)) {
  1986. window.location.replace(
  1987. cleanPath(base + '/#' + location)
  1988. );
  1989. return true
  1990. }
  1991. }
  1992. function ensureSlash () {
  1993. const path = getHash();
  1994. if (path.charAt(0) === '/') {
  1995. return true
  1996. }
  1997. replaceHash('/' + path);
  1998. return false
  1999. }
  2000. function getHash () {
  2001. // We can't use window.location.hash here because it's not
  2002. // consistent across browsers - Firefox will pre-decode it!
  2003. let href = window.location.href;
  2004. const index = href.indexOf('#');
  2005. // empty path
  2006. if (index < 0) return ''
  2007. href = href.slice(index + 1);
  2008. // decode the hash but not the search or hash
  2009. // as search(query) is already decoded
  2010. // https://github.com/vuejs/vue-router/issues/2708
  2011. const searchIndex = href.indexOf('?');
  2012. if (searchIndex < 0) {
  2013. const hashIndex = href.indexOf('#');
  2014. if (hashIndex > -1) href = decodeURI(href.slice(0, hashIndex)) + href.slice(hashIndex);
  2015. else href = decodeURI(href);
  2016. } else {
  2017. if (searchIndex > -1) href = decodeURI(href.slice(0, searchIndex)) + href.slice(searchIndex);
  2018. }
  2019. return href
  2020. }
  2021. function getUrl (path) {
  2022. const href = window.location.href;
  2023. const i = href.indexOf('#');
  2024. const base = i >= 0 ? href.slice(0, i) : href;
  2025. return `${base}#${path}`
  2026. }
  2027. function pushHash (path) {
  2028. if (supportsPushState) {
  2029. pushState(getUrl(path));
  2030. } else {
  2031. window.location.hash = path;
  2032. }
  2033. }
  2034. function replaceHash (path) {
  2035. if (supportsPushState) {
  2036. replaceState(getUrl(path));
  2037. } else {
  2038. window.location.replace(getUrl(path));
  2039. }
  2040. }
  2041. /* */
  2042. class AbstractHistory extends History {
  2043. constructor (router, base) {
  2044. super(router, base);
  2045. this.stack = [];
  2046. this.index = -1;
  2047. }
  2048. push (location, onComplete, onAbort) {
  2049. this.transitionTo(location, route => {
  2050. this.stack = this.stack.slice(0, this.index + 1).concat(route);
  2051. this.index++;
  2052. onComplete && onComplete(route);
  2053. }, onAbort);
  2054. }
  2055. replace (location, onComplete, onAbort) {
  2056. this.transitionTo(location, route => {
  2057. this.stack = this.stack.slice(0, this.index).concat(route);
  2058. onComplete && onComplete(route);
  2059. }, onAbort);
  2060. }
  2061. go (n) {
  2062. const targetIndex = this.index + n;
  2063. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2064. return
  2065. }
  2066. const route = this.stack[targetIndex];
  2067. this.confirmTransition(route, () => {
  2068. this.index = targetIndex;
  2069. this.updateRoute(route);
  2070. });
  2071. }
  2072. getCurrentLocation () {
  2073. const current = this.stack[this.stack.length - 1];
  2074. return current ? current.fullPath : '/'
  2075. }
  2076. ensureURL () {
  2077. // noop
  2078. }
  2079. }
  2080. /* */
  2081. class VueRouter {
  2082. constructor (options = {}) {
  2083. this.app = null;
  2084. this.apps = [];
  2085. this.options = options;
  2086. this.beforeHooks = [];
  2087. this.resolveHooks = [];
  2088. this.afterHooks = [];
  2089. this.matcher = createMatcher(options.routes || [], this);
  2090. let mode = options.mode || 'hash';
  2091. this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
  2092. if (this.fallback) {
  2093. mode = 'hash';
  2094. }
  2095. if (!inBrowser) {
  2096. mode = 'abstract';
  2097. }
  2098. this.mode = mode;
  2099. switch (mode) {
  2100. case 'history':
  2101. this.history = new HTML5History(this, options.base);
  2102. break
  2103. case 'hash':
  2104. this.history = new HashHistory(this, options.base, this.fallback);
  2105. break
  2106. case 'abstract':
  2107. this.history = new AbstractHistory(this, options.base);
  2108. break
  2109. default:
  2110. {
  2111. assert(false, `invalid mode: ${mode}`);
  2112. }
  2113. }
  2114. }
  2115. match (
  2116. raw,
  2117. current,
  2118. redirectedFrom
  2119. ) {
  2120. return this.matcher.match(raw, current, redirectedFrom)
  2121. }
  2122. get currentRoute () {
  2123. return this.history && this.history.current
  2124. }
  2125. init (app /* Vue component instance */) {
  2126. "development" !== 'production' && assert(
  2127. install.installed,
  2128. `not installed. Make sure to call \`Vue.use(VueRouter)\` ` +
  2129. `before creating root instance.`
  2130. );
  2131. this.apps.push(app);
  2132. // set up app destroyed handler
  2133. // https://github.com/vuejs/vue-router/issues/2639
  2134. app.$once('hook:destroyed', () => {
  2135. // clean out app from this.apps array once destroyed
  2136. const index = this.apps.indexOf(app);
  2137. if (index > -1) this.apps.splice(index, 1);
  2138. // ensure we still have a main app or null if no apps
  2139. // we do not release the router so it can be reused
  2140. if (this.app === app) this.app = this.apps[0] || null;
  2141. });
  2142. // main app previously initialized
  2143. // return as we don't need to set up new history listener
  2144. if (this.app) {
  2145. return
  2146. }
  2147. this.app = app;
  2148. const history = this.history;
  2149. if (history instanceof HTML5History) {
  2150. history.transitionTo(history.getCurrentLocation());
  2151. } else if (history instanceof HashHistory) {
  2152. const setupHashListener = () => {
  2153. history.setupListeners();
  2154. };
  2155. history.transitionTo(
  2156. history.getCurrentLocation(),
  2157. setupHashListener,
  2158. setupHashListener
  2159. );
  2160. }
  2161. history.listen(route => {
  2162. this.apps.forEach((app) => {
  2163. app._route = route;
  2164. });
  2165. });
  2166. }
  2167. beforeEach (fn) {
  2168. return registerHook(this.beforeHooks, fn)
  2169. }
  2170. beforeResolve (fn) {
  2171. return registerHook(this.resolveHooks, fn)
  2172. }
  2173. afterEach (fn) {
  2174. return registerHook(this.afterHooks, fn)
  2175. }
  2176. onReady (cb, errorCb) {
  2177. this.history.onReady(cb, errorCb);
  2178. }
  2179. onError (errorCb) {
  2180. this.history.onError(errorCb);
  2181. }
  2182. push (location, onComplete, onAbort) {
  2183. this.history.push(location, onComplete, onAbort);
  2184. }
  2185. replace (location, onComplete, onAbort) {
  2186. this.history.replace(location, onComplete, onAbort);
  2187. }
  2188. go (n) {
  2189. this.history.go(n);
  2190. }
  2191. back () {
  2192. this.go(-1);
  2193. }
  2194. forward () {
  2195. this.go(1);
  2196. }
  2197. getMatchedComponents (to) {
  2198. const route = to
  2199. ? to.matched
  2200. ? to
  2201. : this.resolve(to).route
  2202. : this.currentRoute;
  2203. if (!route) {
  2204. return []
  2205. }
  2206. return [].concat.apply([], route.matched.map(m => {
  2207. return Object.keys(m.components).map(key => {
  2208. return m.components[key]
  2209. })
  2210. }))
  2211. }
  2212. resolve (
  2213. to,
  2214. current,
  2215. append
  2216. ) {
  2217. current = current || this.history.current;
  2218. const location = normalizeLocation(
  2219. to,
  2220. current,
  2221. append,
  2222. this
  2223. );
  2224. const route = this.match(location, current);
  2225. const fullPath = route.redirectedFrom || route.fullPath;
  2226. const base = this.history.base;
  2227. const href = createHref(base, fullPath, this.mode);
  2228. return {
  2229. location,
  2230. route,
  2231. href,
  2232. // for backwards compat
  2233. normalizedTo: location,
  2234. resolved: route
  2235. }
  2236. }
  2237. addRoutes (routes) {
  2238. this.matcher.addRoutes(routes);
  2239. if (this.history.current !== START) {
  2240. this.history.transitionTo(this.history.getCurrentLocation());
  2241. }
  2242. }
  2243. }
  2244. function registerHook (list, fn) {
  2245. list.push(fn);
  2246. return () => {
  2247. const i = list.indexOf(fn);
  2248. if (i > -1) list.splice(i, 1);
  2249. }
  2250. }
  2251. function createHref (base, fullPath, mode) {
  2252. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2253. return base ? cleanPath(base + '/' + path) : path
  2254. }
  2255. VueRouter.install = install;
  2256. VueRouter.version = '3.0.6';
  2257. if (inBrowser && window.Vue) {
  2258. window.Vue.use(VueRouter);
  2259. }
  2260. export default VueRouter;