vue-router.esm.browser.js 73 KB

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