vue-router.esm.js 81 KB

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