vue-router.js 82 KB

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