vue-router.esm.browser.js 73 KB

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