vue-router.js 60 KB

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