vue-router.esm.browser.js 71 KB

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