vue-router.js 92 KB

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