vue-router.esm.browser.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871
  1. /*!
  2. * vue-router v3.1.6
  3. * (c) 2020 Evan You
  4. * @license MIT
  5. */
  6. /* */
  7. function assert (condition, message) {
  8. if (!condition) {
  9. throw new Error(`[vue-router] ${message}`)
  10. }
  11. }
  12. function warn (condition, message) {
  13. if ( !condition) {
  14. typeof console !== 'undefined' && console.warn(`[vue-router] ${message}`);
  15. }
  16. }
  17. function isError (err) {
  18. return Object.prototype.toString.call(err).indexOf('Error') > -1
  19. }
  20. function isExtendedError (constructor, err) {
  21. return (
  22. err instanceof constructor ||
  23. // _name is to support IE9 too
  24. (err && (err.name === constructor.name || err._name === constructor._name))
  25. )
  26. }
  27. function extend (a, b) {
  28. for (const key in b) {
  29. a[key] = b[key];
  30. }
  31. return a
  32. }
  33. var View = {
  34. name: 'RouterView',
  35. functional: true,
  36. props: {
  37. name: {
  38. type: String,
  39. default: 'default'
  40. }
  41. },
  42. render (_, { props, children, parent, data }) {
  43. // used by devtools to display a router-view badge
  44. data.routerView = true;
  45. // directly use parent context's createElement() function
  46. // so that components rendered by router-view can resolve named slots
  47. const h = parent.$createElement;
  48. const name = props.name;
  49. const route = parent.$route;
  50. const cache = parent._routerViewCache || (parent._routerViewCache = {});
  51. // determine current view depth, also check to see if the tree
  52. // has been toggled inactive but kept-alive.
  53. let depth = 0;
  54. let inactive = false;
  55. while (parent && parent._routerRoot !== parent) {
  56. const vnodeData = parent.$vnode ? parent.$vnode.data : {};
  57. if (vnodeData.routerView) {
  58. depth++;
  59. }
  60. if (vnodeData.keepAlive && parent._directInactive && parent._inactive) {
  61. inactive = true;
  62. }
  63. parent = parent.$parent;
  64. }
  65. data.routerViewDepth = depth;
  66. // render previous view if the tree is inactive and kept-alive
  67. if (inactive) {
  68. const cachedData = cache[name];
  69. const cachedComponent = cachedData && cachedData.component;
  70. if (cachedComponent) {
  71. // #2301
  72. // pass props
  73. if (cachedData.configProps) {
  74. fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
  75. }
  76. return h(cachedComponent, data, children)
  77. } else {
  78. // render previous empty view
  79. return h()
  80. }
  81. }
  82. const matched = route.matched[depth];
  83. const component = matched && matched.components[name];
  84. // render empty node if no matched route or no config component
  85. if (!matched || !component) {
  86. cache[name] = null;
  87. return h()
  88. }
  89. // cache component
  90. cache[name] = { component };
  91. // attach instance registration hook
  92. // this will be called in the instance's injected lifecycle hooks
  93. data.registerRouteInstance = (vm, val) => {
  94. // val could be undefined for unregistration
  95. const current = matched.instances[name];
  96. if (
  97. (val && current !== vm) ||
  98. (!val && current === vm)
  99. ) {
  100. matched.instances[name] = val;
  101. }
  102. }
  103. // also register instance in prepatch hook
  104. // in case the same component instance is reused across different routes
  105. ;(data.hook || (data.hook = {})).prepatch = (_, vnode) => {
  106. matched.instances[name] = vnode.componentInstance;
  107. };
  108. // register instance in init hook
  109. // in case kept-alive component be actived when routes changed
  110. data.hook.init = (vnode) => {
  111. if (vnode.data.keepAlive &&
  112. vnode.componentInstance &&
  113. vnode.componentInstance !== matched.instances[name]
  114. ) {
  115. matched.instances[name] = vnode.componentInstance;
  116. }
  117. };
  118. const configProps = matched.props && matched.props[name];
  119. // save route and configProps in cachce
  120. if (configProps) {
  121. extend(cache[name], {
  122. route,
  123. configProps
  124. });
  125. fillPropsinData(component, data, route, configProps);
  126. }
  127. return h(component, data, children)
  128. }
  129. };
  130. function fillPropsinData (component, data, route, configProps) {
  131. // resolve props
  132. let propsToPass = data.props = resolveProps(route, configProps);
  133. if (propsToPass) {
  134. // clone to prevent mutation
  135. propsToPass = data.props = extend({}, propsToPass);
  136. // pass non-declared props as attrs
  137. const attrs = data.attrs = data.attrs || {};
  138. for (const key in propsToPass) {
  139. if (!component.props || !(key in component.props)) {
  140. attrs[key] = propsToPass[key];
  141. delete propsToPass[key];
  142. }
  143. }
  144. }
  145. }
  146. function resolveProps (route, config) {
  147. switch (typeof config) {
  148. case 'undefined':
  149. return
  150. case 'object':
  151. return config
  152. case 'function':
  153. return config(route)
  154. case 'boolean':
  155. return config ? route.params : undefined
  156. default:
  157. {
  158. warn(
  159. false,
  160. `props in "${route.path}" is a ${typeof config}, ` +
  161. `expecting an object, function or boolean.`
  162. );
  163. }
  164. }
  165. }
  166. /* */
  167. const encodeReserveRE = /[!'()*]/g;
  168. const encodeReserveReplacer = c => '%' + c.charCodeAt(0).toString(16);
  169. const commaRE = /%2C/g;
  170. // fixed encodeURIComponent which is more conformant to RFC3986:
  171. // - escapes [!'()*]
  172. // - preserve commas
  173. const encode = str => encodeURIComponent(str)
  174. .replace(encodeReserveRE, encodeReserveReplacer)
  175. .replace(commaRE, ',');
  176. const decode = decodeURIComponent;
  177. function resolveQuery (
  178. query,
  179. extraQuery = {},
  180. _parseQuery
  181. ) {
  182. const parse = _parseQuery || parseQuery;
  183. let parsedQuery;
  184. try {
  185. parsedQuery = parse(query || '');
  186. } catch (e) {
  187. warn(false, e.message);
  188. parsedQuery = {};
  189. }
  190. for (const key in extraQuery) {
  191. parsedQuery[key] = extraQuery[key];
  192. }
  193. return parsedQuery
  194. }
  195. function parseQuery (query) {
  196. const res = {};
  197. query = query.trim().replace(/^(\?|#|&)/, '');
  198. if (!query) {
  199. return res
  200. }
  201. query.split('&').forEach(param => {
  202. const parts = param.replace(/\+/g, ' ').split('=');
  203. const key = decode(parts.shift());
  204. const val = parts.length > 0
  205. ? decode(parts.join('='))
  206. : null;
  207. if (res[key] === undefined) {
  208. res[key] = val;
  209. } else if (Array.isArray(res[key])) {
  210. res[key].push(val);
  211. } else {
  212. res[key] = [res[key], val];
  213. }
  214. });
  215. return res
  216. }
  217. function stringifyQuery (obj) {
  218. const res = obj ? Object.keys(obj).map(key => {
  219. const val = obj[key];
  220. if (val === undefined) {
  221. return ''
  222. }
  223. if (val === null) {
  224. return encode(key)
  225. }
  226. if (Array.isArray(val)) {
  227. const result = [];
  228. val.forEach(val2 => {
  229. if (val2 === undefined) {
  230. return
  231. }
  232. if (val2 === null) {
  233. result.push(encode(key));
  234. } else {
  235. result.push(encode(key) + '=' + encode(val2));
  236. }
  237. });
  238. return result.join('&')
  239. }
  240. return encode(key) + '=' + encode(val)
  241. }).filter(x => x.length > 0).join('&') : null;
  242. return res ? `?${res}` : ''
  243. }
  244. /* */
  245. const trailingSlashRE = /\/?$/;
  246. function createRoute (
  247. record,
  248. location,
  249. redirectedFrom,
  250. router
  251. ) {
  252. const stringifyQuery = router && router.options.stringifyQuery;
  253. let query = location.query || {};
  254. try {
  255. query = clone(query);
  256. } catch (e) {}
  257. const route = {
  258. name: location.name || (record && record.name),
  259. meta: (record && record.meta) || {},
  260. path: location.path || '/',
  261. hash: location.hash || '',
  262. query,
  263. params: location.params || {},
  264. fullPath: getFullPath(location, stringifyQuery),
  265. matched: record ? formatMatch(record) : []
  266. };
  267. if (redirectedFrom) {
  268. route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
  269. }
  270. return Object.freeze(route)
  271. }
  272. function clone (value) {
  273. if (Array.isArray(value)) {
  274. return value.map(clone)
  275. } else if (value && typeof value === 'object') {
  276. const res = {};
  277. for (const key in value) {
  278. res[key] = clone(value[key]);
  279. }
  280. return res
  281. } else {
  282. return value
  283. }
  284. }
  285. // the starting route that represents the initial state
  286. const START = createRoute(null, {
  287. path: '/'
  288. });
  289. function formatMatch (record) {
  290. const res = [];
  291. while (record) {
  292. res.unshift(record);
  293. record = record.parent;
  294. }
  295. return res
  296. }
  297. function getFullPath (
  298. { path, query = {}, hash = '' },
  299. _stringifyQuery
  300. ) {
  301. const stringify = _stringifyQuery || stringifyQuery;
  302. return (path || '/') + stringify(query) + hash
  303. }
  304. function isSameRoute (a, b) {
  305. if (b === START) {
  306. return a === b
  307. } else if (!b) {
  308. return false
  309. } else if (a.path && b.path) {
  310. return (
  311. a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
  312. a.hash === b.hash &&
  313. isObjectEqual(a.query, b.query)
  314. )
  315. } else if (a.name && b.name) {
  316. return (
  317. a.name === b.name &&
  318. a.hash === b.hash &&
  319. isObjectEqual(a.query, b.query) &&
  320. isObjectEqual(a.params, b.params)
  321. )
  322. } else {
  323. return false
  324. }
  325. }
  326. function isObjectEqual (a = {}, b = {}) {
  327. // handle null value #1566
  328. if (!a || !b) return a === b
  329. const aKeys = Object.keys(a);
  330. const bKeys = Object.keys(b);
  331. if (aKeys.length !== bKeys.length) {
  332. return false
  333. }
  334. return aKeys.every(key => {
  335. const aVal = a[key];
  336. const bVal = b[key];
  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))
  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) {
  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 + ')$');
  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.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. 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 handler = e => {
  929. if (guardEvent(e)) {
  930. if (this.replace) {
  931. router.replace(location, noop);
  932. } else {
  933. router.push(location, noop);
  934. }
  935. }
  936. };
  937. const on = { click: guardEvent };
  938. if (Array.isArray(this.event)) {
  939. this.event.forEach(e => {
  940. on[e] = handler;
  941. });
  942. } else {
  943. on[this.event] = handler;
  944. }
  945. const data = { class: classes };
  946. const scopedSlot =
  947. !this.$scopedSlots.$hasNormal &&
  948. this.$scopedSlots.default &&
  949. this.$scopedSlots.default({
  950. href,
  951. route,
  952. navigate: handler,
  953. isActive: classes[activeClass],
  954. isExactActive: classes[exactActiveClass]
  955. });
  956. if (scopedSlot) {
  957. if (scopedSlot.length === 1) {
  958. return scopedSlot[0]
  959. } else if (scopedSlot.length > 1 || !scopedSlot.length) {
  960. {
  961. warn(
  962. false,
  963. `RouterLink with to="${
  964. this.to
  965. }" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.`
  966. );
  967. }
  968. return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
  969. }
  970. }
  971. if (this.tag === 'a') {
  972. data.on = on;
  973. data.attrs = { href };
  974. } else {
  975. // find the first <a> child and apply listener and href
  976. const a = findAnchor(this.$slots.default);
  977. if (a) {
  978. // in case the <a> is a static node
  979. a.isStatic = false;
  980. const aData = (a.data = extend({}, a.data));
  981. aData.on = aData.on || {};
  982. // transform existing events in both objects into arrays so we can push later
  983. for (const event in aData.on) {
  984. const handler = aData.on[event];
  985. if (event in on) {
  986. aData.on[event] = Array.isArray(handler) ? handler : [handler];
  987. }
  988. }
  989. // append new listeners for router-link
  990. for (const event in on) {
  991. if (event in aData.on) {
  992. // on[event] is always a function
  993. aData.on[event].push(on[event]);
  994. } else {
  995. aData.on[event] = handler;
  996. }
  997. }
  998. const aAttrs = (a.data.attrs = extend({}, a.data.attrs));
  999. aAttrs.href = href;
  1000. } else {
  1001. // doesn't have <a> child, apply listener to self
  1002. data.on = on;
  1003. }
  1004. }
  1005. return h(this.tag, data, this.$slots.default)
  1006. }
  1007. };
  1008. function guardEvent (e) {
  1009. // don't redirect with control keys
  1010. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return
  1011. // don't redirect when preventDefault called
  1012. if (e.defaultPrevented) return
  1013. // don't redirect on right click
  1014. if (e.button !== undefined && e.button !== 0) return
  1015. // don't redirect if `target="_blank"`
  1016. if (e.currentTarget && e.currentTarget.getAttribute) {
  1017. const target = e.currentTarget.getAttribute('target');
  1018. if (/\b_blank\b/i.test(target)) return
  1019. }
  1020. // this may be a Weex event which doesn't have this method
  1021. if (e.preventDefault) {
  1022. e.preventDefault();
  1023. }
  1024. return true
  1025. }
  1026. function findAnchor (children) {
  1027. if (children) {
  1028. let child;
  1029. for (let i = 0; i < children.length; i++) {
  1030. child = children[i];
  1031. if (child.tag === 'a') {
  1032. return child
  1033. }
  1034. if (child.children && (child = findAnchor(child.children))) {
  1035. return child
  1036. }
  1037. }
  1038. }
  1039. }
  1040. let _Vue;
  1041. function install (Vue) {
  1042. if (install.installed && _Vue === Vue) return
  1043. install.installed = true;
  1044. _Vue = Vue;
  1045. const isDef = v => v !== undefined;
  1046. const registerInstance = (vm, callVal) => {
  1047. let i = vm.$options._parentVnode;
  1048. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  1049. i(vm, callVal);
  1050. }
  1051. };
  1052. Vue.mixin({
  1053. beforeCreate () {
  1054. if (isDef(this.$options.router)) {
  1055. this._routerRoot = this;
  1056. this._router = this.$options.router;
  1057. this._router.init(this);
  1058. Vue.util.defineReactive(this, '_route', this._router.history.current);
  1059. } else {
  1060. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  1061. }
  1062. registerInstance(this, this);
  1063. },
  1064. destroyed () {
  1065. registerInstance(this);
  1066. }
  1067. });
  1068. Object.defineProperty(Vue.prototype, '$router', {
  1069. get () { return this._routerRoot._router }
  1070. });
  1071. Object.defineProperty(Vue.prototype, '$route', {
  1072. get () { return this._routerRoot._route }
  1073. });
  1074. Vue.component('RouterView', View);
  1075. Vue.component('RouterLink', Link);
  1076. const strats = Vue.config.optionMergeStrategies;
  1077. // use the same hook merging strategy for route hooks
  1078. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  1079. }
  1080. /* */
  1081. const inBrowser = typeof window !== 'undefined';
  1082. /* */
  1083. function createRouteMap (
  1084. routes,
  1085. oldPathList,
  1086. oldPathMap,
  1087. oldNameMap
  1088. ) {
  1089. // the path list is used to control path matching priority
  1090. const pathList = oldPathList || [];
  1091. // $flow-disable-line
  1092. const pathMap = oldPathMap || Object.create(null);
  1093. // $flow-disable-line
  1094. const nameMap = oldNameMap || Object.create(null);
  1095. routes.forEach(route => {
  1096. addRouteRecord(pathList, pathMap, nameMap, route);
  1097. });
  1098. // ensure wildcard routes are always at the end
  1099. for (let i = 0, l = pathList.length; i < l; i++) {
  1100. if (pathList[i] === '*') {
  1101. pathList.push(pathList.splice(i, 1)[0]);
  1102. l--;
  1103. i--;
  1104. }
  1105. }
  1106. {
  1107. // warn if routes do not include leading slashes
  1108. const found = pathList
  1109. // check for missing leading slash
  1110. .filter(path => path && path.charAt(0) !== '*' && path.charAt(0) !== '/');
  1111. if (found.length > 0) {
  1112. const pathNames = found.map(path => `- ${path}`).join('\n');
  1113. warn(false, `Non-nested routes must include a leading slash character. Fix the following routes: \n${pathNames}`);
  1114. }
  1115. }
  1116. return {
  1117. pathList,
  1118. pathMap,
  1119. nameMap
  1120. }
  1121. }
  1122. function addRouteRecord (
  1123. pathList,
  1124. pathMap,
  1125. nameMap,
  1126. route,
  1127. parent,
  1128. matchAs
  1129. ) {
  1130. const { path, name } = route;
  1131. {
  1132. assert(path != null, `"path" is required in a route configuration.`);
  1133. assert(
  1134. typeof route.component !== 'string',
  1135. `route config "component" for path: ${String(
  1136. path || name
  1137. )} cannot be a ` + `string id. Use an actual component instead.`
  1138. );
  1139. }
  1140. const pathToRegexpOptions =
  1141. route.pathToRegexpOptions || {};
  1142. const normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
  1143. if (typeof route.caseSensitive === 'boolean') {
  1144. pathToRegexpOptions.sensitive = route.caseSensitive;
  1145. }
  1146. const record = {
  1147. path: normalizedPath,
  1148. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1149. components: route.components || { default: route.component },
  1150. instances: {},
  1151. name,
  1152. parent,
  1153. matchAs,
  1154. redirect: route.redirect,
  1155. beforeEnter: route.beforeEnter,
  1156. meta: route.meta || {},
  1157. props:
  1158. route.props == null
  1159. ? {}
  1160. : route.components
  1161. ? route.props
  1162. : { default: route.props }
  1163. };
  1164. if (route.children) {
  1165. // Warn if route is named, does not redirect and has a default child route.
  1166. // If users navigate to this route by name, the default child will
  1167. // not be rendered (GH Issue #629)
  1168. {
  1169. if (
  1170. route.name &&
  1171. !route.redirect &&
  1172. route.children.some(child => /^\/?$/.test(child.path))
  1173. ) {
  1174. warn(
  1175. false,
  1176. `Named Route '${route.name}' has a default child route. ` +
  1177. `When navigating to this named route (:to="{name: '${
  1178. route.name
  1179. }'"), ` +
  1180. `the default child route will not be rendered. Remove the name from ` +
  1181. `this route and use the name of the default child route for named ` +
  1182. `links instead.`
  1183. );
  1184. }
  1185. }
  1186. route.children.forEach(child => {
  1187. const childMatchAs = matchAs
  1188. ? cleanPath(`${matchAs}/${child.path}`)
  1189. : undefined;
  1190. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1191. });
  1192. }
  1193. if (!pathMap[record.path]) {
  1194. pathList.push(record.path);
  1195. pathMap[record.path] = record;
  1196. }
  1197. if (route.alias !== undefined) {
  1198. const aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
  1199. for (let i = 0; i < aliases.length; ++i) {
  1200. const alias = aliases[i];
  1201. if ( alias === path) {
  1202. warn(
  1203. false,
  1204. `Found an alias with the same value as the path: "${path}". You have to remove that alias. It will be ignored in development.`
  1205. );
  1206. // skip in dev to make it work
  1207. continue
  1208. }
  1209. const aliasRoute = {
  1210. path: alias,
  1211. children: route.children
  1212. };
  1213. addRouteRecord(
  1214. pathList,
  1215. pathMap,
  1216. nameMap,
  1217. aliasRoute,
  1218. parent,
  1219. record.path || '/' // matchAs
  1220. );
  1221. }
  1222. }
  1223. if (name) {
  1224. if (!nameMap[name]) {
  1225. nameMap[name] = record;
  1226. } else if ( !matchAs) {
  1227. warn(
  1228. false,
  1229. `Duplicate named routes definition: ` +
  1230. `{ name: "${name}", path: "${record.path}" }`
  1231. );
  1232. }
  1233. }
  1234. }
  1235. function compileRouteRegex (
  1236. path,
  1237. pathToRegexpOptions
  1238. ) {
  1239. const regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1240. {
  1241. const keys = Object.create(null);
  1242. regex.keys.forEach(key => {
  1243. warn(
  1244. !keys[key.name],
  1245. `Duplicate param keys in route with path: "${path}"`
  1246. );
  1247. keys[key.name] = true;
  1248. });
  1249. }
  1250. return regex
  1251. }
  1252. function normalizePath (
  1253. path,
  1254. parent,
  1255. strict
  1256. ) {
  1257. if (!strict) path = path.replace(/\/$/, '');
  1258. if (path[0] === '/') return path
  1259. if (parent == null) return path
  1260. return cleanPath(`${parent.path}/${path}`)
  1261. }
  1262. /* */
  1263. function createMatcher (
  1264. routes,
  1265. router
  1266. ) {
  1267. const { pathList, pathMap, nameMap } = createRouteMap(routes);
  1268. function addRoutes (routes) {
  1269. createRouteMap(routes, pathList, pathMap, nameMap);
  1270. }
  1271. function match (
  1272. raw,
  1273. currentRoute,
  1274. redirectedFrom
  1275. ) {
  1276. const location = normalizeLocation(raw, currentRoute, false, router);
  1277. const { name } = location;
  1278. if (name) {
  1279. const record = nameMap[name];
  1280. {
  1281. warn(record, `Route with name '${name}' does not exist`);
  1282. }
  1283. if (!record) return _createRoute(null, location)
  1284. const paramNames = record.regex.keys
  1285. .filter(key => !key.optional)
  1286. .map(key => key.name);
  1287. if (typeof location.params !== 'object') {
  1288. location.params = {};
  1289. }
  1290. if (currentRoute && typeof currentRoute.params === 'object') {
  1291. for (const key in currentRoute.params) {
  1292. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1293. location.params[key] = currentRoute.params[key];
  1294. }
  1295. }
  1296. }
  1297. location.path = fillParams(record.path, location.params, `named route "${name}"`);
  1298. return _createRoute(record, location, redirectedFrom)
  1299. } else if (location.path) {
  1300. location.params = {};
  1301. for (let i = 0; i < pathList.length; i++) {
  1302. const path = pathList[i];
  1303. const record = pathMap[path];
  1304. if (matchRoute(record.regex, location.path, location.params)) {
  1305. return _createRoute(record, location, redirectedFrom)
  1306. }
  1307. }
  1308. }
  1309. // no match
  1310. return _createRoute(null, location)
  1311. }
  1312. function redirect (
  1313. record,
  1314. location
  1315. ) {
  1316. const originalRedirect = record.redirect;
  1317. let redirect = typeof originalRedirect === 'function'
  1318. ? originalRedirect(createRoute(record, location, null, router))
  1319. : originalRedirect;
  1320. if (typeof redirect === 'string') {
  1321. redirect = { path: redirect };
  1322. }
  1323. if (!redirect || typeof redirect !== 'object') {
  1324. {
  1325. warn(
  1326. false, `invalid redirect option: ${JSON.stringify(redirect)}`
  1327. );
  1328. }
  1329. return _createRoute(null, location)
  1330. }
  1331. const re = redirect;
  1332. const { name, path } = re;
  1333. let { query, hash, params } = location;
  1334. query = re.hasOwnProperty('query') ? re.query : query;
  1335. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1336. params = re.hasOwnProperty('params') ? re.params : params;
  1337. if (name) {
  1338. // resolved named direct
  1339. const targetRecord = nameMap[name];
  1340. {
  1341. assert(targetRecord, `redirect failed: named route "${name}" not found.`);
  1342. }
  1343. return match({
  1344. _normalized: true,
  1345. name,
  1346. query,
  1347. hash,
  1348. params
  1349. }, undefined, location)
  1350. } else if (path) {
  1351. // 1. resolve relative redirect
  1352. const rawPath = resolveRecordPath(path, record);
  1353. // 2. resolve params
  1354. const resolvedPath = fillParams(rawPath, params, `redirect route with path "${rawPath}"`);
  1355. // 3. rematch with existing query and hash
  1356. return match({
  1357. _normalized: true,
  1358. path: resolvedPath,
  1359. query,
  1360. hash
  1361. }, undefined, location)
  1362. } else {
  1363. {
  1364. warn(false, `invalid redirect option: ${JSON.stringify(redirect)}`);
  1365. }
  1366. return _createRoute(null, location)
  1367. }
  1368. }
  1369. function alias (
  1370. record,
  1371. location,
  1372. matchAs
  1373. ) {
  1374. const aliasedPath = fillParams(matchAs, location.params, `aliased route with path "${matchAs}"`);
  1375. const aliasedMatch = match({
  1376. _normalized: true,
  1377. path: aliasedPath
  1378. });
  1379. if (aliasedMatch) {
  1380. const matched = aliasedMatch.matched;
  1381. const aliasedRecord = matched[matched.length - 1];
  1382. location.params = aliasedMatch.params;
  1383. return _createRoute(aliasedRecord, location)
  1384. }
  1385. return _createRoute(null, location)
  1386. }
  1387. function _createRoute (
  1388. record,
  1389. location,
  1390. redirectedFrom
  1391. ) {
  1392. if (record && record.redirect) {
  1393. return redirect(record, redirectedFrom || location)
  1394. }
  1395. if (record && record.matchAs) {
  1396. return alias(record, location, record.matchAs)
  1397. }
  1398. return createRoute(record, location, redirectedFrom, router)
  1399. }
  1400. return {
  1401. match,
  1402. addRoutes
  1403. }
  1404. }
  1405. function matchRoute (
  1406. regex,
  1407. path,
  1408. params
  1409. ) {
  1410. const m = path.match(regex);
  1411. if (!m) {
  1412. return false
  1413. } else if (!params) {
  1414. return true
  1415. }
  1416. for (let i = 1, len = m.length; i < len; ++i) {
  1417. const key = regex.keys[i - 1];
  1418. const val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
  1419. if (key) {
  1420. // Fix #1994: using * with props: true generates a param named 0
  1421. params[key.name || 'pathMatch'] = val;
  1422. }
  1423. }
  1424. return true
  1425. }
  1426. function resolveRecordPath (path, record) {
  1427. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1428. }
  1429. /* */
  1430. // use User Timing api (if present) for more accurate key precision
  1431. const Time =
  1432. inBrowser && window.performance && window.performance.now
  1433. ? window.performance
  1434. : Date;
  1435. function genStateKey () {
  1436. return Time.now().toFixed(3)
  1437. }
  1438. let _key = genStateKey();
  1439. function getStateKey () {
  1440. return _key
  1441. }
  1442. function setStateKey (key) {
  1443. return (_key = key)
  1444. }
  1445. /* */
  1446. const positionStore = Object.create(null);
  1447. function setupScroll () {
  1448. // Fix for #1585 for Firefox
  1449. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1450. // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
  1451. // window.location.protocol + '//' + window.location.host
  1452. // location.host contains the port and location.hostname doesn't
  1453. const protocolAndPath = window.location.protocol + '//' + window.location.host;
  1454. const absolutePath = window.location.href.replace(protocolAndPath, '');
  1455. // preserve existing history state as it could be overriden by the user
  1456. const stateCopy = extend({}, window.history.state);
  1457. stateCopy.key = getStateKey();
  1458. window.history.replaceState(stateCopy, '', absolutePath);
  1459. window.addEventListener('popstate', e => {
  1460. saveScrollPosition();
  1461. if (e.state && e.state.key) {
  1462. setStateKey(e.state.key);
  1463. }
  1464. });
  1465. }
  1466. function handleScroll (
  1467. router,
  1468. to,
  1469. from,
  1470. isPop
  1471. ) {
  1472. if (!router.app) {
  1473. return
  1474. }
  1475. const behavior = router.options.scrollBehavior;
  1476. if (!behavior) {
  1477. return
  1478. }
  1479. {
  1480. assert(typeof behavior === 'function', `scrollBehavior must be a function`);
  1481. }
  1482. // wait until re-render finishes before scrolling
  1483. router.app.$nextTick(() => {
  1484. const position = getScrollPosition();
  1485. const shouldScroll = behavior.call(
  1486. router,
  1487. to,
  1488. from,
  1489. isPop ? position : null
  1490. );
  1491. if (!shouldScroll) {
  1492. return
  1493. }
  1494. if (typeof shouldScroll.then === 'function') {
  1495. shouldScroll
  1496. .then(shouldScroll => {
  1497. scrollToPosition((shouldScroll), position);
  1498. })
  1499. .catch(err => {
  1500. {
  1501. assert(false, err.toString());
  1502. }
  1503. });
  1504. } else {
  1505. scrollToPosition(shouldScroll, position);
  1506. }
  1507. });
  1508. }
  1509. function saveScrollPosition () {
  1510. const key = getStateKey();
  1511. if (key) {
  1512. positionStore[key] = {
  1513. x: window.pageXOffset,
  1514. y: window.pageYOffset
  1515. };
  1516. }
  1517. }
  1518. function getScrollPosition () {
  1519. const key = getStateKey();
  1520. if (key) {
  1521. return positionStore[key]
  1522. }
  1523. }
  1524. function getElementPosition (el, offset) {
  1525. const docEl = document.documentElement;
  1526. const docRect = docEl.getBoundingClientRect();
  1527. const elRect = el.getBoundingClientRect();
  1528. return {
  1529. x: elRect.left - docRect.left - offset.x,
  1530. y: elRect.top - docRect.top - offset.y
  1531. }
  1532. }
  1533. function isValidPosition (obj) {
  1534. return isNumber(obj.x) || isNumber(obj.y)
  1535. }
  1536. function normalizePosition (obj) {
  1537. return {
  1538. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1539. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1540. }
  1541. }
  1542. function normalizeOffset (obj) {
  1543. return {
  1544. x: isNumber(obj.x) ? obj.x : 0,
  1545. y: isNumber(obj.y) ? obj.y : 0
  1546. }
  1547. }
  1548. function isNumber (v) {
  1549. return typeof v === 'number'
  1550. }
  1551. const hashStartsWithNumberRE = /^#\d/;
  1552. function scrollToPosition (shouldScroll, position) {
  1553. const isObject = typeof shouldScroll === 'object';
  1554. if (isObject && typeof shouldScroll.selector === 'string') {
  1555. // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
  1556. // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
  1557. const el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
  1558. ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
  1559. : document.querySelector(shouldScroll.selector);
  1560. if (el) {
  1561. let offset =
  1562. shouldScroll.offset && typeof shouldScroll.offset === 'object'
  1563. ? shouldScroll.offset
  1564. : {};
  1565. offset = normalizeOffset(offset);
  1566. position = getElementPosition(el, offset);
  1567. } else if (isValidPosition(shouldScroll)) {
  1568. position = normalizePosition(shouldScroll);
  1569. }
  1570. } else if (isObject && isValidPosition(shouldScroll)) {
  1571. position = normalizePosition(shouldScroll);
  1572. }
  1573. if (position) {
  1574. window.scrollTo(position.x, position.y);
  1575. }
  1576. }
  1577. /* */
  1578. const supportsPushState =
  1579. inBrowser &&
  1580. (function () {
  1581. const ua = window.navigator.userAgent;
  1582. if (
  1583. (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
  1584. ua.indexOf('Mobile Safari') !== -1 &&
  1585. ua.indexOf('Chrome') === -1 &&
  1586. ua.indexOf('Windows Phone') === -1
  1587. ) {
  1588. return false
  1589. }
  1590. return window.history && 'pushState' in window.history
  1591. })();
  1592. function pushState (url, replace) {
  1593. saveScrollPosition();
  1594. // try...catch the pushState call to get around Safari
  1595. // DOM Exception 18 where it limits to 100 pushState calls
  1596. const history = window.history;
  1597. try {
  1598. if (replace) {
  1599. // preserve existing history state as it could be overriden by the user
  1600. const stateCopy = extend({}, history.state);
  1601. stateCopy.key = getStateKey();
  1602. history.replaceState(stateCopy, '', url);
  1603. } else {
  1604. history.pushState({ key: setStateKey(genStateKey()) }, '', url);
  1605. }
  1606. } catch (e) {
  1607. window.location[replace ? 'replace' : 'assign'](url);
  1608. }
  1609. }
  1610. function replaceState (url) {
  1611. pushState(url, true);
  1612. }
  1613. /* */
  1614. function runQueue (queue, fn, cb) {
  1615. const step = index => {
  1616. if (index >= queue.length) {
  1617. cb();
  1618. } else {
  1619. if (queue[index]) {
  1620. fn(queue[index], () => {
  1621. step(index + 1);
  1622. });
  1623. } else {
  1624. step(index + 1);
  1625. }
  1626. }
  1627. };
  1628. step(0);
  1629. }
  1630. /* */
  1631. function resolveAsyncComponents (matched) {
  1632. return (to, from, next) => {
  1633. let hasAsync = false;
  1634. let pending = 0;
  1635. let error = null;
  1636. flatMapComponents(matched, (def, _, match, key) => {
  1637. // if it's a function and doesn't have cid attached,
  1638. // assume it's an async component resolve function.
  1639. // we are not using Vue's default async resolving mechanism because
  1640. // we want to halt the navigation until the incoming component has been
  1641. // resolved.
  1642. if (typeof def === 'function' && def.cid === undefined) {
  1643. hasAsync = true;
  1644. pending++;
  1645. const resolve = once(resolvedDef => {
  1646. if (isESModule(resolvedDef)) {
  1647. resolvedDef = resolvedDef.default;
  1648. }
  1649. // save resolved on async factory in case it's used elsewhere
  1650. def.resolved = typeof resolvedDef === 'function'
  1651. ? resolvedDef
  1652. : _Vue.extend(resolvedDef);
  1653. match.components[key] = resolvedDef;
  1654. pending--;
  1655. if (pending <= 0) {
  1656. next();
  1657. }
  1658. });
  1659. const reject = once(reason => {
  1660. const msg = `Failed to resolve async component ${key}: ${reason}`;
  1661. warn(false, msg);
  1662. if (!error) {
  1663. error = isError(reason)
  1664. ? reason
  1665. : new Error(msg);
  1666. next(error);
  1667. }
  1668. });
  1669. let res;
  1670. try {
  1671. res = def(resolve, reject);
  1672. } catch (e) {
  1673. reject(e);
  1674. }
  1675. if (res) {
  1676. if (typeof res.then === 'function') {
  1677. res.then(resolve, reject);
  1678. } else {
  1679. // new syntax in Vue 2.3
  1680. const comp = res.component;
  1681. if (comp && typeof comp.then === 'function') {
  1682. comp.then(resolve, reject);
  1683. }
  1684. }
  1685. }
  1686. }
  1687. });
  1688. if (!hasAsync) next();
  1689. }
  1690. }
  1691. function flatMapComponents (
  1692. matched,
  1693. fn
  1694. ) {
  1695. return flatten(matched.map(m => {
  1696. return Object.keys(m.components).map(key => fn(
  1697. m.components[key],
  1698. m.instances[key],
  1699. m, key
  1700. ))
  1701. }))
  1702. }
  1703. function flatten (arr) {
  1704. return Array.prototype.concat.apply([], arr)
  1705. }
  1706. const hasSymbol =
  1707. typeof Symbol === 'function' &&
  1708. typeof Symbol.toStringTag === 'symbol';
  1709. function isESModule (obj) {
  1710. return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  1711. }
  1712. // in Webpack 2, require.ensure now also returns a Promise
  1713. // so the resolve/reject functions may get called an extra time
  1714. // if the user uses an arrow function shorthand that happens to
  1715. // return that Promise.
  1716. function once (fn) {
  1717. let called = false;
  1718. return function (...args) {
  1719. if (called) return
  1720. called = true;
  1721. return fn.apply(this, args)
  1722. }
  1723. }
  1724. class NavigationDuplicated extends Error {
  1725. constructor (normalizedLocation) {
  1726. super();
  1727. this.name = this._name = 'NavigationDuplicated';
  1728. // passing the message to super() doesn't seem to work in the transpiled version
  1729. this.message = `Navigating to current location ("${
  1730. normalizedLocation.fullPath
  1731. }") is not allowed`;
  1732. // add a stack property so services like Sentry can correctly display it
  1733. Object.defineProperty(this, 'stack', {
  1734. value: new Error().stack,
  1735. writable: true,
  1736. configurable: true
  1737. });
  1738. // we could also have used
  1739. // Error.captureStackTrace(this, this.constructor)
  1740. // but it only exists on node and chrome
  1741. }
  1742. }
  1743. // support IE9
  1744. NavigationDuplicated._name = 'NavigationDuplicated';
  1745. /* */
  1746. class History {
  1747. // implemented by sub-classes
  1748. constructor (router, base) {
  1749. this.router = router;
  1750. this.base = normalizeBase(base);
  1751. // start with a route object that stands for "nowhere"
  1752. this.current = START;
  1753. this.pending = null;
  1754. this.ready = false;
  1755. this.readyCbs = [];
  1756. this.readyErrorCbs = [];
  1757. this.errorCbs = [];
  1758. }
  1759. listen (cb) {
  1760. this.cb = cb;
  1761. }
  1762. onReady (cb, errorCb) {
  1763. if (this.ready) {
  1764. cb();
  1765. } else {
  1766. this.readyCbs.push(cb);
  1767. if (errorCb) {
  1768. this.readyErrorCbs.push(errorCb);
  1769. }
  1770. }
  1771. }
  1772. onError (errorCb) {
  1773. this.errorCbs.push(errorCb);
  1774. }
  1775. transitionTo (
  1776. location,
  1777. onComplete,
  1778. onAbort
  1779. ) {
  1780. const route = this.router.match(location, this.current);
  1781. this.confirmTransition(
  1782. route,
  1783. () => {
  1784. this.updateRoute(route);
  1785. onComplete && onComplete(route);
  1786. this.ensureURL();
  1787. // fire ready cbs once
  1788. if (!this.ready) {
  1789. this.ready = true;
  1790. this.readyCbs.forEach(cb => {
  1791. cb(route);
  1792. });
  1793. }
  1794. },
  1795. err => {
  1796. if (onAbort) {
  1797. onAbort(err);
  1798. }
  1799. if (err && !this.ready) {
  1800. this.ready = true;
  1801. this.readyErrorCbs.forEach(cb => {
  1802. cb(err);
  1803. });
  1804. }
  1805. }
  1806. );
  1807. }
  1808. confirmTransition (route, onComplete, onAbort) {
  1809. const current = this.current;
  1810. const abort = err => {
  1811. // after merging https://github.com/vuejs/vue-router/pull/2771 we
  1812. // When the user navigates through history through back/forward buttons
  1813. // we do not want to throw the error. We only throw it if directly calling
  1814. // push/replace. That's why it's not included in isError
  1815. if (!isExtendedError(NavigationDuplicated, err) && isError(err)) {
  1816. if (this.errorCbs.length) {
  1817. this.errorCbs.forEach(cb => {
  1818. cb(err);
  1819. });
  1820. } else {
  1821. warn(false, 'uncaught error during route navigation:');
  1822. console.error(err);
  1823. }
  1824. }
  1825. onAbort && onAbort(err);
  1826. };
  1827. if (
  1828. isSameRoute(route, current) &&
  1829. // in the case the route map has been dynamically appended to
  1830. route.matched.length === current.matched.length
  1831. ) {
  1832. this.ensureURL();
  1833. return abort(new NavigationDuplicated(route))
  1834. }
  1835. const { updated, deactivated, activated } = resolveQueue(
  1836. this.current.matched,
  1837. route.matched
  1838. );
  1839. const queue = [].concat(
  1840. // in-component leave guards
  1841. extractLeaveGuards(deactivated),
  1842. // global before hooks
  1843. this.router.beforeHooks,
  1844. // in-component update hooks
  1845. extractUpdateHooks(updated),
  1846. // in-config enter guards
  1847. activated.map(m => m.beforeEnter),
  1848. // async components
  1849. resolveAsyncComponents(activated)
  1850. );
  1851. this.pending = route;
  1852. const iterator = (hook, next) => {
  1853. if (this.pending !== route) {
  1854. return abort()
  1855. }
  1856. try {
  1857. hook(route, current, (to) => {
  1858. if (to === false || isError(to)) {
  1859. // next(false) -> abort navigation, ensure current URL
  1860. this.ensureURL(true);
  1861. abort(to);
  1862. } else if (
  1863. typeof to === 'string' ||
  1864. (typeof to === 'object' &&
  1865. (typeof to.path === 'string' || typeof to.name === 'string'))
  1866. ) {
  1867. // next('/') or next({ path: '/' }) -> redirect
  1868. abort();
  1869. if (typeof to === 'object' && to.replace) {
  1870. this.replace(to);
  1871. } else {
  1872. this.push(to);
  1873. }
  1874. } else {
  1875. // confirm transition and pass on the value
  1876. next(to);
  1877. }
  1878. });
  1879. } catch (e) {
  1880. abort(e);
  1881. }
  1882. };
  1883. runQueue(queue, iterator, () => {
  1884. const postEnterCbs = [];
  1885. const isValid = () => this.current === route;
  1886. // wait until async components are resolved before
  1887. // extracting in-component enter guards
  1888. const enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
  1889. const queue = enterGuards.concat(this.router.resolveHooks);
  1890. runQueue(queue, iterator, () => {
  1891. if (this.pending !== route) {
  1892. return abort()
  1893. }
  1894. this.pending = null;
  1895. onComplete(route);
  1896. if (this.router.app) {
  1897. this.router.app.$nextTick(() => {
  1898. postEnterCbs.forEach(cb => {
  1899. cb();
  1900. });
  1901. });
  1902. }
  1903. });
  1904. });
  1905. }
  1906. updateRoute (route) {
  1907. const prev = this.current;
  1908. this.current = route;
  1909. this.cb && this.cb(route);
  1910. this.router.afterHooks.forEach(hook => {
  1911. hook && hook(route, prev);
  1912. });
  1913. }
  1914. }
  1915. function normalizeBase (base) {
  1916. if (!base) {
  1917. if (inBrowser) {
  1918. // respect <base> tag
  1919. const baseEl = document.querySelector('base');
  1920. base = (baseEl && baseEl.getAttribute('href')) || '/';
  1921. // strip full URL origin
  1922. base = base.replace(/^https?:\/\/[^\/]+/, '');
  1923. } else {
  1924. base = '/';
  1925. }
  1926. }
  1927. // make sure there's the starting slash
  1928. if (base.charAt(0) !== '/') {
  1929. base = '/' + base;
  1930. }
  1931. // remove trailing slash
  1932. return base.replace(/\/$/, '')
  1933. }
  1934. function resolveQueue (
  1935. current,
  1936. next
  1937. ) {
  1938. let i;
  1939. const max = Math.max(current.length, next.length);
  1940. for (i = 0; i < max; i++) {
  1941. if (current[i] !== next[i]) {
  1942. break
  1943. }
  1944. }
  1945. return {
  1946. updated: next.slice(0, i),
  1947. activated: next.slice(i),
  1948. deactivated: current.slice(i)
  1949. }
  1950. }
  1951. function extractGuards (
  1952. records,
  1953. name,
  1954. bind,
  1955. reverse
  1956. ) {
  1957. const guards = flatMapComponents(records, (def, instance, match, key) => {
  1958. const guard = extractGuard(def, name);
  1959. if (guard) {
  1960. return Array.isArray(guard)
  1961. ? guard.map(guard => bind(guard, instance, match, key))
  1962. : bind(guard, instance, match, key)
  1963. }
  1964. });
  1965. return flatten(reverse ? guards.reverse() : guards)
  1966. }
  1967. function extractGuard (
  1968. def,
  1969. key
  1970. ) {
  1971. if (typeof def !== 'function') {
  1972. // extend now so that global mixins are applied.
  1973. def = _Vue.extend(def);
  1974. }
  1975. return def.options[key]
  1976. }
  1977. function extractLeaveGuards (deactivated) {
  1978. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  1979. }
  1980. function extractUpdateHooks (updated) {
  1981. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  1982. }
  1983. function bindGuard (guard, instance) {
  1984. if (instance) {
  1985. return function boundRouteGuard () {
  1986. return guard.apply(instance, arguments)
  1987. }
  1988. }
  1989. }
  1990. function extractEnterGuards (
  1991. activated,
  1992. cbs,
  1993. isValid
  1994. ) {
  1995. return extractGuards(
  1996. activated,
  1997. 'beforeRouteEnter',
  1998. (guard, _, match, key) => {
  1999. return bindEnterGuard(guard, match, key, cbs, isValid)
  2000. }
  2001. )
  2002. }
  2003. function bindEnterGuard (
  2004. guard,
  2005. match,
  2006. key,
  2007. cbs,
  2008. isValid
  2009. ) {
  2010. return function routeEnterGuard (to, from, next) {
  2011. return guard(to, from, cb => {
  2012. if (typeof cb === 'function') {
  2013. cbs.push(() => {
  2014. // #750
  2015. // if a router-view is wrapped with an out-in transition,
  2016. // the instance may not have been registered at this time.
  2017. // we will need to poll for registration until current route
  2018. // is no longer valid.
  2019. poll(cb, match.instances, key, isValid);
  2020. });
  2021. }
  2022. next(cb);
  2023. })
  2024. }
  2025. }
  2026. function poll (
  2027. cb, // somehow flow cannot infer this is a function
  2028. instances,
  2029. key,
  2030. isValid
  2031. ) {
  2032. if (
  2033. instances[key] &&
  2034. !instances[key]._isBeingDestroyed // do not reuse being destroyed instance
  2035. ) {
  2036. cb(instances[key]);
  2037. } else if (isValid()) {
  2038. setTimeout(() => {
  2039. poll(cb, instances, key, isValid);
  2040. }, 16);
  2041. }
  2042. }
  2043. /* */
  2044. class HTML5History extends History {
  2045. constructor (router, base) {
  2046. super(router, base);
  2047. const expectScroll = router.options.scrollBehavior;
  2048. const supportsScroll = supportsPushState && expectScroll;
  2049. if (supportsScroll) {
  2050. setupScroll();
  2051. }
  2052. const initLocation = getLocation(this.base);
  2053. window.addEventListener('popstate', e => {
  2054. const current = this.current;
  2055. // Avoiding first `popstate` event dispatched in some browsers but first
  2056. // history route not updated since async guard at the same time.
  2057. const location = getLocation(this.base);
  2058. if (this.current === START && location === initLocation) {
  2059. return
  2060. }
  2061. this.transitionTo(location, route => {
  2062. if (supportsScroll) {
  2063. handleScroll(router, route, current, true);
  2064. }
  2065. });
  2066. });
  2067. }
  2068. go (n) {
  2069. window.history.go(n);
  2070. }
  2071. push (location, onComplete, onAbort) {
  2072. const { current: fromRoute } = this;
  2073. this.transitionTo(location, route => {
  2074. pushState(cleanPath(this.base + route.fullPath));
  2075. handleScroll(this.router, route, fromRoute, false);
  2076. onComplete && onComplete(route);
  2077. }, onAbort);
  2078. }
  2079. replace (location, onComplete, onAbort) {
  2080. const { current: fromRoute } = this;
  2081. this.transitionTo(location, route => {
  2082. replaceState(cleanPath(this.base + route.fullPath));
  2083. handleScroll(this.router, route, fromRoute, false);
  2084. onComplete && onComplete(route);
  2085. }, onAbort);
  2086. }
  2087. ensureURL (push) {
  2088. if (getLocation(this.base) !== this.current.fullPath) {
  2089. const current = cleanPath(this.base + this.current.fullPath);
  2090. push ? pushState(current) : replaceState(current);
  2091. }
  2092. }
  2093. getCurrentLocation () {
  2094. return getLocation(this.base)
  2095. }
  2096. }
  2097. function getLocation (base) {
  2098. let path = decodeURI(window.location.pathname);
  2099. if (base && path.indexOf(base) === 0) {
  2100. path = path.slice(base.length);
  2101. }
  2102. return (path || '/') + window.location.search + window.location.hash
  2103. }
  2104. /* */
  2105. class HashHistory extends History {
  2106. constructor (router, base, fallback) {
  2107. super(router, base);
  2108. // check history fallback deeplinking
  2109. if (fallback && checkFallback(this.base)) {
  2110. return
  2111. }
  2112. ensureSlash();
  2113. }
  2114. // this is delayed until the app mounts
  2115. // to avoid the hashchange listener being fired too early
  2116. setupListeners () {
  2117. const router = this.router;
  2118. const expectScroll = router.options.scrollBehavior;
  2119. const supportsScroll = supportsPushState && expectScroll;
  2120. if (supportsScroll) {
  2121. setupScroll();
  2122. }
  2123. window.addEventListener(
  2124. supportsPushState ? 'popstate' : 'hashchange',
  2125. () => {
  2126. const current = this.current;
  2127. if (!ensureSlash()) {
  2128. return
  2129. }
  2130. this.transitionTo(getHash(), route => {
  2131. if (supportsScroll) {
  2132. handleScroll(this.router, route, current, true);
  2133. }
  2134. if (!supportsPushState) {
  2135. replaceHash(route.fullPath);
  2136. }
  2137. });
  2138. }
  2139. );
  2140. }
  2141. push (location, onComplete, onAbort) {
  2142. const { current: fromRoute } = this;
  2143. this.transitionTo(
  2144. location,
  2145. route => {
  2146. pushHash(route.fullPath);
  2147. handleScroll(this.router, route, fromRoute, false);
  2148. onComplete && onComplete(route);
  2149. },
  2150. onAbort
  2151. );
  2152. }
  2153. replace (location, onComplete, onAbort) {
  2154. const { current: fromRoute } = this;
  2155. this.transitionTo(
  2156. location,
  2157. route => {
  2158. replaceHash(route.fullPath);
  2159. handleScroll(this.router, route, fromRoute, false);
  2160. onComplete && onComplete(route);
  2161. },
  2162. onAbort
  2163. );
  2164. }
  2165. go (n) {
  2166. window.history.go(n);
  2167. }
  2168. ensureURL (push) {
  2169. const current = this.current.fullPath;
  2170. if (getHash() !== current) {
  2171. push ? pushHash(current) : replaceHash(current);
  2172. }
  2173. }
  2174. getCurrentLocation () {
  2175. return getHash()
  2176. }
  2177. }
  2178. function checkFallback (base) {
  2179. const location = getLocation(base);
  2180. if (!/^\/#/.test(location)) {
  2181. window.location.replace(cleanPath(base + '/#' + location));
  2182. return true
  2183. }
  2184. }
  2185. function ensureSlash () {
  2186. const path = getHash();
  2187. if (path.charAt(0) === '/') {
  2188. return true
  2189. }
  2190. replaceHash('/' + path);
  2191. return false
  2192. }
  2193. function getHash () {
  2194. // We can't use window.location.hash here because it's not
  2195. // consistent across browsers - Firefox will pre-decode it!
  2196. let href = window.location.href;
  2197. const index = href.indexOf('#');
  2198. // empty path
  2199. if (index < 0) return ''
  2200. href = href.slice(index + 1);
  2201. // decode the hash but not the search or hash
  2202. // as search(query) is already decoded
  2203. // https://github.com/vuejs/vue-router/issues/2708
  2204. const searchIndex = href.indexOf('?');
  2205. if (searchIndex < 0) {
  2206. const hashIndex = href.indexOf('#');
  2207. if (hashIndex > -1) {
  2208. href = decodeURI(href.slice(0, hashIndex)) + href.slice(hashIndex);
  2209. } else href = decodeURI(href);
  2210. } else {
  2211. href = decodeURI(href.slice(0, searchIndex)) + href.slice(searchIndex);
  2212. }
  2213. return href
  2214. }
  2215. function getUrl (path) {
  2216. const href = window.location.href;
  2217. const i = href.indexOf('#');
  2218. const base = i >= 0 ? href.slice(0, i) : href;
  2219. return `${base}#${path}`
  2220. }
  2221. function pushHash (path) {
  2222. if (supportsPushState) {
  2223. pushState(getUrl(path));
  2224. } else {
  2225. window.location.hash = path;
  2226. }
  2227. }
  2228. function replaceHash (path) {
  2229. if (supportsPushState) {
  2230. replaceState(getUrl(path));
  2231. } else {
  2232. window.location.replace(getUrl(path));
  2233. }
  2234. }
  2235. /* */
  2236. class AbstractHistory extends History {
  2237. constructor (router, base) {
  2238. super(router, base);
  2239. this.stack = [];
  2240. this.index = -1;
  2241. }
  2242. push (location, onComplete, onAbort) {
  2243. this.transitionTo(
  2244. location,
  2245. route => {
  2246. this.stack = this.stack.slice(0, this.index + 1).concat(route);
  2247. this.index++;
  2248. onComplete && onComplete(route);
  2249. },
  2250. onAbort
  2251. );
  2252. }
  2253. replace (location, onComplete, onAbort) {
  2254. this.transitionTo(
  2255. location,
  2256. route => {
  2257. this.stack = this.stack.slice(0, this.index).concat(route);
  2258. onComplete && onComplete(route);
  2259. },
  2260. onAbort
  2261. );
  2262. }
  2263. go (n) {
  2264. const targetIndex = this.index + n;
  2265. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2266. return
  2267. }
  2268. const route = this.stack[targetIndex];
  2269. this.confirmTransition(
  2270. route,
  2271. () => {
  2272. this.index = targetIndex;
  2273. this.updateRoute(route);
  2274. },
  2275. err => {
  2276. if (isExtendedError(NavigationDuplicated, err)) {
  2277. this.index = targetIndex;
  2278. }
  2279. }
  2280. );
  2281. }
  2282. getCurrentLocation () {
  2283. const current = this.stack[this.stack.length - 1];
  2284. return current ? current.fullPath : '/'
  2285. }
  2286. ensureURL () {
  2287. // noop
  2288. }
  2289. }
  2290. /* */
  2291. class VueRouter {
  2292. constructor (options = {}) {
  2293. this.app = null;
  2294. this.apps = [];
  2295. this.options = options;
  2296. this.beforeHooks = [];
  2297. this.resolveHooks = [];
  2298. this.afterHooks = [];
  2299. this.matcher = createMatcher(options.routes || [], this);
  2300. let mode = options.mode || 'hash';
  2301. this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
  2302. if (this.fallback) {
  2303. mode = 'hash';
  2304. }
  2305. if (!inBrowser) {
  2306. mode = 'abstract';
  2307. }
  2308. this.mode = mode;
  2309. switch (mode) {
  2310. case 'history':
  2311. this.history = new HTML5History(this, options.base);
  2312. break
  2313. case 'hash':
  2314. this.history = new HashHistory(this, options.base, this.fallback);
  2315. break
  2316. case 'abstract':
  2317. this.history = new AbstractHistory(this, options.base);
  2318. break
  2319. default:
  2320. {
  2321. assert(false, `invalid mode: ${mode}`);
  2322. }
  2323. }
  2324. }
  2325. match (
  2326. raw,
  2327. current,
  2328. redirectedFrom
  2329. ) {
  2330. return this.matcher.match(raw, current, redirectedFrom)
  2331. }
  2332. get currentRoute () {
  2333. return this.history && this.history.current
  2334. }
  2335. init (app /* Vue component instance */) {
  2336. assert(
  2337. install.installed,
  2338. `not installed. Make sure to call \`Vue.use(VueRouter)\` ` +
  2339. `before creating root instance.`
  2340. );
  2341. this.apps.push(app);
  2342. // set up app destroyed handler
  2343. // https://github.com/vuejs/vue-router/issues/2639
  2344. app.$once('hook:destroyed', () => {
  2345. // clean out app from this.apps array once destroyed
  2346. const index = this.apps.indexOf(app);
  2347. if (index > -1) this.apps.splice(index, 1);
  2348. // ensure we still have a main app or null if no apps
  2349. // we do not release the router so it can be reused
  2350. if (this.app === app) this.app = this.apps[0] || null;
  2351. });
  2352. // main app previously initialized
  2353. // return as we don't need to set up new history listener
  2354. if (this.app) {
  2355. return
  2356. }
  2357. this.app = app;
  2358. const history = this.history;
  2359. if (history instanceof HTML5History) {
  2360. history.transitionTo(history.getCurrentLocation());
  2361. } else if (history instanceof HashHistory) {
  2362. const setupHashListener = () => {
  2363. history.setupListeners();
  2364. };
  2365. history.transitionTo(
  2366. history.getCurrentLocation(),
  2367. setupHashListener,
  2368. setupHashListener
  2369. );
  2370. }
  2371. history.listen(route => {
  2372. this.apps.forEach((app) => {
  2373. app._route = route;
  2374. });
  2375. });
  2376. }
  2377. beforeEach (fn) {
  2378. return registerHook(this.beforeHooks, fn)
  2379. }
  2380. beforeResolve (fn) {
  2381. return registerHook(this.resolveHooks, fn)
  2382. }
  2383. afterEach (fn) {
  2384. return registerHook(this.afterHooks, fn)
  2385. }
  2386. onReady (cb, errorCb) {
  2387. this.history.onReady(cb, errorCb);
  2388. }
  2389. onError (errorCb) {
  2390. this.history.onError(errorCb);
  2391. }
  2392. push (location, onComplete, onAbort) {
  2393. // $flow-disable-line
  2394. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2395. return new Promise((resolve, reject) => {
  2396. this.history.push(location, resolve, reject);
  2397. })
  2398. } else {
  2399. this.history.push(location, onComplete, onAbort);
  2400. }
  2401. }
  2402. replace (location, onComplete, onAbort) {
  2403. // $flow-disable-line
  2404. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2405. return new Promise((resolve, reject) => {
  2406. this.history.replace(location, resolve, reject);
  2407. })
  2408. } else {
  2409. this.history.replace(location, onComplete, onAbort);
  2410. }
  2411. }
  2412. go (n) {
  2413. this.history.go(n);
  2414. }
  2415. back () {
  2416. this.go(-1);
  2417. }
  2418. forward () {
  2419. this.go(1);
  2420. }
  2421. getMatchedComponents (to) {
  2422. const route = to
  2423. ? to.matched
  2424. ? to
  2425. : this.resolve(to).route
  2426. : this.currentRoute;
  2427. if (!route) {
  2428. return []
  2429. }
  2430. return [].concat.apply([], route.matched.map(m => {
  2431. return Object.keys(m.components).map(key => {
  2432. return m.components[key]
  2433. })
  2434. }))
  2435. }
  2436. resolve (
  2437. to,
  2438. current,
  2439. append
  2440. ) {
  2441. current = current || this.history.current;
  2442. const location = normalizeLocation(
  2443. to,
  2444. current,
  2445. append,
  2446. this
  2447. );
  2448. const route = this.match(location, current);
  2449. const fullPath = route.redirectedFrom || route.fullPath;
  2450. const base = this.history.base;
  2451. const href = createHref(base, fullPath, this.mode);
  2452. return {
  2453. location,
  2454. route,
  2455. href,
  2456. // for backwards compat
  2457. normalizedTo: location,
  2458. resolved: route
  2459. }
  2460. }
  2461. addRoutes (routes) {
  2462. this.matcher.addRoutes(routes);
  2463. if (this.history.current !== START) {
  2464. this.history.transitionTo(this.history.getCurrentLocation());
  2465. }
  2466. }
  2467. }
  2468. function registerHook (list, fn) {
  2469. list.push(fn);
  2470. return () => {
  2471. const i = list.indexOf(fn);
  2472. if (i > -1) list.splice(i, 1);
  2473. }
  2474. }
  2475. function createHref (base, fullPath, mode) {
  2476. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2477. return base ? cleanPath(base + '/' + path) : path
  2478. }
  2479. VueRouter.install = install;
  2480. VueRouter.version = '3.1.6';
  2481. if (inBrowser && window.Vue) {
  2482. window.Vue.use(VueRouter);
  2483. }
  2484. export default VueRouter;