vue-router.esm.js 77 KB

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