vue-router.esm.js 77 KB

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