vue-router.esm.browser.js 62 KB

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