vue-router.esm.browser.js 73 KB

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