vue-router.common.js 77 KB

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