vue-router.esm.browser.js 76 KB

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