vue-router.js 82 KB

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