vue-router.common.js 78 KB

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