vue-router.esm.js 78 KB

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