vuex.esm.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. /*!
  2. * vuex v3.5.1
  3. * (c) 2020 Evan You
  4. * @license MIT
  5. */
  6. function applyMixin (Vue) {
  7. var version = Number(Vue.version.split('.')[0]);
  8. if (version >= 2) {
  9. Vue.mixin({ beforeCreate: vuexInit });
  10. } else {
  11. // override init and inject vuex init procedure
  12. // for 1.x backwards compatibility.
  13. var _init = Vue.prototype._init;
  14. Vue.prototype._init = function (options) {
  15. if ( options === void 0 ) options = {};
  16. options.init = options.init
  17. ? [vuexInit].concat(options.init)
  18. : vuexInit;
  19. _init.call(this, options);
  20. };
  21. }
  22. /**
  23. * Vuex init hook, injected into each instances init hooks list.
  24. */
  25. function vuexInit () {
  26. var options = this.$options;
  27. // store injection
  28. if (options.store) {
  29. this.$store = typeof options.store === 'function'
  30. ? options.store()
  31. : options.store;
  32. } else if (options.parent && options.parent.$store) {
  33. this.$store = options.parent.$store;
  34. }
  35. }
  36. }
  37. var target = typeof window !== 'undefined'
  38. ? window
  39. : typeof global !== 'undefined'
  40. ? global
  41. : {};
  42. var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
  43. function devtoolPlugin (store) {
  44. if (!devtoolHook) { return }
  45. store._devtoolHook = devtoolHook;
  46. devtoolHook.emit('vuex:init', store);
  47. devtoolHook.on('vuex:travel-to-state', function (targetState) {
  48. store.replaceState(targetState);
  49. });
  50. store.subscribe(function (mutation, state) {
  51. devtoolHook.emit('vuex:mutation', mutation, state);
  52. }, { prepend: true });
  53. store.subscribeAction(function (action, state) {
  54. devtoolHook.emit('vuex:action', action, state);
  55. }, { prepend: true });
  56. }
  57. /**
  58. * Get the first item that pass the test
  59. * by second argument function
  60. *
  61. * @param {Array} list
  62. * @param {Function} f
  63. * @return {*}
  64. */
  65. function find (list, f) {
  66. return list.filter(f)[0]
  67. }
  68. /**
  69. * Deep copy the given object considering circular structure.
  70. * This function caches all nested objects and its copies.
  71. * If it detects circular structure, use cached copy to avoid infinite loop.
  72. *
  73. * @param {*} obj
  74. * @param {Array<Object>} cache
  75. * @return {*}
  76. */
  77. function deepCopy (obj, cache) {
  78. if ( cache === void 0 ) cache = [];
  79. // just return if obj is immutable value
  80. if (obj === null || typeof obj !== 'object') {
  81. return obj
  82. }
  83. // if obj is hit, it is in circular structure
  84. var hit = find(cache, function (c) { return c.original === obj; });
  85. if (hit) {
  86. return hit.copy
  87. }
  88. var copy = Array.isArray(obj) ? [] : {};
  89. // put the copy into cache at first
  90. // because we want to refer it in recursive deepCopy
  91. cache.push({
  92. original: obj,
  93. copy: copy
  94. });
  95. Object.keys(obj).forEach(function (key) {
  96. copy[key] = deepCopy(obj[key], cache);
  97. });
  98. return copy
  99. }
  100. /**
  101. * forEach for object
  102. */
  103. function forEachValue (obj, fn) {
  104. Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
  105. }
  106. function isObject (obj) {
  107. return obj !== null && typeof obj === 'object'
  108. }
  109. function isPromise (val) {
  110. return val && typeof val.then === 'function'
  111. }
  112. function assert (condition, msg) {
  113. if (!condition) { throw new Error(("[vuex] " + msg)) }
  114. }
  115. function partial (fn, arg) {
  116. return function () {
  117. return fn(arg)
  118. }
  119. }
  120. // Base data struct for store's module, package with some attribute and method
  121. var Module = function Module (rawModule, runtime) {
  122. this.runtime = runtime;
  123. // Store some children item
  124. this._children = Object.create(null);
  125. // Store the origin module object which passed by programmer
  126. this._rawModule = rawModule;
  127. var rawState = rawModule.state;
  128. // Store the origin module's state
  129. this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
  130. };
  131. var prototypeAccessors = { namespaced: { configurable: true } };
  132. prototypeAccessors.namespaced.get = function () {
  133. return !!this._rawModule.namespaced
  134. };
  135. Module.prototype.addChild = function addChild (key, module) {
  136. this._children[key] = module;
  137. };
  138. Module.prototype.removeChild = function removeChild (key) {
  139. delete this._children[key];
  140. };
  141. Module.prototype.getChild = function getChild (key) {
  142. return this._children[key]
  143. };
  144. Module.prototype.hasChild = function hasChild (key) {
  145. return key in this._children
  146. };
  147. Module.prototype.update = function update (rawModule) {
  148. this._rawModule.namespaced = rawModule.namespaced;
  149. if (rawModule.actions) {
  150. this._rawModule.actions = rawModule.actions;
  151. }
  152. if (rawModule.mutations) {
  153. this._rawModule.mutations = rawModule.mutations;
  154. }
  155. if (rawModule.getters) {
  156. this._rawModule.getters = rawModule.getters;
  157. }
  158. };
  159. Module.prototype.forEachChild = function forEachChild (fn) {
  160. forEachValue(this._children, fn);
  161. };
  162. Module.prototype.forEachGetter = function forEachGetter (fn) {
  163. if (this._rawModule.getters) {
  164. forEachValue(this._rawModule.getters, fn);
  165. }
  166. };
  167. Module.prototype.forEachAction = function forEachAction (fn) {
  168. if (this._rawModule.actions) {
  169. forEachValue(this._rawModule.actions, fn);
  170. }
  171. };
  172. Module.prototype.forEachMutation = function forEachMutation (fn) {
  173. if (this._rawModule.mutations) {
  174. forEachValue(this._rawModule.mutations, fn);
  175. }
  176. };
  177. Object.defineProperties( Module.prototype, prototypeAccessors );
  178. var ModuleCollection = function ModuleCollection (rawRootModule) {
  179. // register root module (Vuex.Store options)
  180. this.register([], rawRootModule, false);
  181. };
  182. ModuleCollection.prototype.get = function get (path) {
  183. return path.reduce(function (module, key) {
  184. return module.getChild(key)
  185. }, this.root)
  186. };
  187. ModuleCollection.prototype.getNamespace = function getNamespace (path) {
  188. var module = this.root;
  189. return path.reduce(function (namespace, key) {
  190. module = module.getChild(key);
  191. return namespace + (module.namespaced ? key + '/' : '')
  192. }, '')
  193. };
  194. ModuleCollection.prototype.update = function update$1 (rawRootModule) {
  195. update([], this.root, rawRootModule);
  196. };
  197. ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
  198. var this$1 = this;
  199. if ( runtime === void 0 ) runtime = true;
  200. if ((process.env.NODE_ENV !== 'production')) {
  201. assertRawModule(path, rawModule);
  202. }
  203. var newModule = new Module(rawModule, runtime);
  204. if (path.length === 0) {
  205. this.root = newModule;
  206. } else {
  207. var parent = this.get(path.slice(0, -1));
  208. parent.addChild(path[path.length - 1], newModule);
  209. }
  210. // register nested modules
  211. if (rawModule.modules) {
  212. forEachValue(rawModule.modules, function (rawChildModule, key) {
  213. this$1.register(path.concat(key), rawChildModule, runtime);
  214. });
  215. }
  216. };
  217. ModuleCollection.prototype.unregister = function unregister (path) {
  218. var parent = this.get(path.slice(0, -1));
  219. var key = path[path.length - 1];
  220. var child = parent.getChild(key);
  221. if (!child) {
  222. if ((process.env.NODE_ENV !== 'production')) {
  223. console.warn(
  224. "[vuex] trying to unregister module '" + key + "', which is " +
  225. "not registered"
  226. );
  227. }
  228. return
  229. }
  230. if (!child.runtime) {
  231. return
  232. }
  233. parent.removeChild(key);
  234. };
  235. ModuleCollection.prototype.isRegistered = function isRegistered (path) {
  236. var parent = this.get(path.slice(0, -1));
  237. var key = path[path.length - 1];
  238. return parent.hasChild(key)
  239. };
  240. function update (path, targetModule, newModule) {
  241. if ((process.env.NODE_ENV !== 'production')) {
  242. assertRawModule(path, newModule);
  243. }
  244. // update target module
  245. targetModule.update(newModule);
  246. // update nested modules
  247. if (newModule.modules) {
  248. for (var key in newModule.modules) {
  249. if (!targetModule.getChild(key)) {
  250. if ((process.env.NODE_ENV !== 'production')) {
  251. console.warn(
  252. "[vuex] trying to add a new module '" + key + "' on hot reloading, " +
  253. 'manual reload is needed'
  254. );
  255. }
  256. return
  257. }
  258. update(
  259. path.concat(key),
  260. targetModule.getChild(key),
  261. newModule.modules[key]
  262. );
  263. }
  264. }
  265. }
  266. var functionAssert = {
  267. assert: function (value) { return typeof value === 'function'; },
  268. expected: 'function'
  269. };
  270. var objectAssert = {
  271. assert: function (value) { return typeof value === 'function' ||
  272. (typeof value === 'object' && typeof value.handler === 'function'); },
  273. expected: 'function or object with "handler" function'
  274. };
  275. var assertTypes = {
  276. getters: functionAssert,
  277. mutations: functionAssert,
  278. actions: objectAssert
  279. };
  280. function assertRawModule (path, rawModule) {
  281. Object.keys(assertTypes).forEach(function (key) {
  282. if (!rawModule[key]) { return }
  283. var assertOptions = assertTypes[key];
  284. forEachValue(rawModule[key], function (value, type) {
  285. assert(
  286. assertOptions.assert(value),
  287. makeAssertionMessage(path, key, type, value, assertOptions.expected)
  288. );
  289. });
  290. });
  291. }
  292. function makeAssertionMessage (path, key, type, value, expected) {
  293. var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
  294. if (path.length > 0) {
  295. buf += " in module \"" + (path.join('.')) + "\"";
  296. }
  297. buf += " is " + (JSON.stringify(value)) + ".";
  298. return buf
  299. }
  300. var Vue; // bind on install
  301. var Store = function Store (options) {
  302. var this$1 = this;
  303. if ( options === void 0 ) options = {};
  304. // Auto install if it is not done yet and `window` has `Vue`.
  305. // To allow users to avoid auto-installation in some cases,
  306. // this code should be placed here. See #731
  307. if (!Vue && typeof window !== 'undefined' && window.Vue) {
  308. install(window.Vue);
  309. }
  310. if ((process.env.NODE_ENV !== 'production')) {
  311. assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
  312. assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
  313. assert(this instanceof Store, "store must be called with the new operator.");
  314. }
  315. var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
  316. var strict = options.strict; if ( strict === void 0 ) strict = false;
  317. // store internal state
  318. this._committing = false;
  319. this._actions = Object.create(null);
  320. this._actionSubscribers = [];
  321. this._mutations = Object.create(null);
  322. this._wrappedGetters = Object.create(null);
  323. this._modules = new ModuleCollection(options);
  324. this._modulesNamespaceMap = Object.create(null);
  325. this._subscribers = [];
  326. this._watcherVM = new Vue();
  327. this._makeLocalGettersCache = Object.create(null);
  328. // bind commit and dispatch to self
  329. var store = this;
  330. var ref = this;
  331. var dispatch = ref.dispatch;
  332. var commit = ref.commit;
  333. this.dispatch = function boundDispatch (type, payload) {
  334. return dispatch.call(store, type, payload)
  335. };
  336. this.commit = function boundCommit (type, payload, options) {
  337. return commit.call(store, type, payload, options)
  338. };
  339. // strict mode
  340. this.strict = strict;
  341. var state = this._modules.root.state;
  342. // init root module.
  343. // this also recursively registers all sub-modules
  344. // and collects all module getters inside this._wrappedGetters
  345. installModule(this, state, [], this._modules.root);
  346. // initialize the store vm, which is responsible for the reactivity
  347. // (also registers _wrappedGetters as computed properties)
  348. resetStoreVM(this, state);
  349. // apply plugins
  350. plugins.forEach(function (plugin) { return plugin(this$1); });
  351. var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
  352. if (useDevtools) {
  353. devtoolPlugin(this);
  354. }
  355. };
  356. var prototypeAccessors$1 = { state: { configurable: true } };
  357. prototypeAccessors$1.state.get = function () {
  358. return this._vm._data.$$state
  359. };
  360. prototypeAccessors$1.state.set = function (v) {
  361. if ((process.env.NODE_ENV !== 'production')) {
  362. assert(false, "use store.replaceState() to explicit replace store state.");
  363. }
  364. };
  365. Store.prototype.commit = function commit (_type, _payload, _options) {
  366. var this$1 = this;
  367. // check object-style commit
  368. var ref = unifyObjectStyle(_type, _payload, _options);
  369. var type = ref.type;
  370. var payload = ref.payload;
  371. var options = ref.options;
  372. var mutation = { type: type, payload: payload };
  373. var entry = this._mutations[type];
  374. if (!entry) {
  375. if ((process.env.NODE_ENV !== 'production')) {
  376. console.error(("[vuex] unknown mutation type: " + type));
  377. }
  378. return
  379. }
  380. this._withCommit(function () {
  381. entry.forEach(function commitIterator (handler) {
  382. handler(payload);
  383. });
  384. });
  385. this._subscribers
  386. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  387. .forEach(function (sub) { return sub(mutation, this$1.state); });
  388. if (
  389. (process.env.NODE_ENV !== 'production') &&
  390. options && options.silent
  391. ) {
  392. console.warn(
  393. "[vuex] mutation type: " + type + ". Silent option has been removed. " +
  394. 'Use the filter functionality in the vue-devtools'
  395. );
  396. }
  397. };
  398. Store.prototype.dispatch = function dispatch (_type, _payload) {
  399. var this$1 = this;
  400. // check object-style dispatch
  401. var ref = unifyObjectStyle(_type, _payload);
  402. var type = ref.type;
  403. var payload = ref.payload;
  404. var action = { type: type, payload: payload };
  405. var entry = this._actions[type];
  406. if (!entry) {
  407. if ((process.env.NODE_ENV !== 'production')) {
  408. console.error(("[vuex] unknown action type: " + type));
  409. }
  410. return
  411. }
  412. try {
  413. this._actionSubscribers
  414. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  415. .filter(function (sub) { return sub.before; })
  416. .forEach(function (sub) { return sub.before(action, this$1.state); });
  417. } catch (e) {
  418. if ((process.env.NODE_ENV !== 'production')) {
  419. console.warn("[vuex] error in before action subscribers: ");
  420. console.error(e);
  421. }
  422. }
  423. var result = entry.length > 1
  424. ? Promise.all(entry.map(function (handler) { return handler(payload); }))
  425. : entry[0](payload);
  426. return new Promise(function (resolve, reject) {
  427. result.then(function (res) {
  428. try {
  429. this$1._actionSubscribers
  430. .filter(function (sub) { return sub.after; })
  431. .forEach(function (sub) { return sub.after(action, this$1.state); });
  432. } catch (e) {
  433. if ((process.env.NODE_ENV !== 'production')) {
  434. console.warn("[vuex] error in after action subscribers: ");
  435. console.error(e);
  436. }
  437. }
  438. resolve(res);
  439. }, function (error) {
  440. try {
  441. this$1._actionSubscribers
  442. .filter(function (sub) { return sub.error; })
  443. .forEach(function (sub) { return sub.error(action, this$1.state, error); });
  444. } catch (e) {
  445. if ((process.env.NODE_ENV !== 'production')) {
  446. console.warn("[vuex] error in error action subscribers: ");
  447. console.error(e);
  448. }
  449. }
  450. reject(error);
  451. });
  452. })
  453. };
  454. Store.prototype.subscribe = function subscribe (fn, options) {
  455. return genericSubscribe(fn, this._subscribers, options)
  456. };
  457. Store.prototype.subscribeAction = function subscribeAction (fn, options) {
  458. var subs = typeof fn === 'function' ? { before: fn } : fn;
  459. return genericSubscribe(subs, this._actionSubscribers, options)
  460. };
  461. Store.prototype.watch = function watch (getter, cb, options) {
  462. var this$1 = this;
  463. if ((process.env.NODE_ENV !== 'production')) {
  464. assert(typeof getter === 'function', "store.watch only accepts a function.");
  465. }
  466. return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
  467. };
  468. Store.prototype.replaceState = function replaceState (state) {
  469. var this$1 = this;
  470. this._withCommit(function () {
  471. this$1._vm._data.$$state = state;
  472. });
  473. };
  474. Store.prototype.registerModule = function registerModule (path, rawModule, options) {
  475. if ( options === void 0 ) options = {};
  476. if (typeof path === 'string') { path = [path]; }
  477. if ((process.env.NODE_ENV !== 'production')) {
  478. assert(Array.isArray(path), "module path must be a string or an Array.");
  479. assert(path.length > 0, 'cannot register the root module by using registerModule.');
  480. }
  481. this._modules.register(path, rawModule);
  482. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  483. // reset store to update getters...
  484. resetStoreVM(this, this.state);
  485. };
  486. Store.prototype.unregisterModule = function unregisterModule (path) {
  487. var this$1 = this;
  488. if (typeof path === 'string') { path = [path]; }
  489. if ((process.env.NODE_ENV !== 'production')) {
  490. assert(Array.isArray(path), "module path must be a string or an Array.");
  491. }
  492. this._modules.unregister(path);
  493. this._withCommit(function () {
  494. var parentState = getNestedState(this$1.state, path.slice(0, -1));
  495. Vue.delete(parentState, path[path.length - 1]);
  496. });
  497. resetStore(this);
  498. };
  499. Store.prototype.hasModule = function hasModule (path) {
  500. if (typeof path === 'string') { path = [path]; }
  501. if ((process.env.NODE_ENV !== 'production')) {
  502. assert(Array.isArray(path), "module path must be a string or an Array.");
  503. }
  504. return this._modules.isRegistered(path)
  505. };
  506. Store.prototype.hotUpdate = function hotUpdate (newOptions) {
  507. this._modules.update(newOptions);
  508. resetStore(this, true);
  509. };
  510. Store.prototype._withCommit = function _withCommit (fn) {
  511. var committing = this._committing;
  512. this._committing = true;
  513. fn();
  514. this._committing = committing;
  515. };
  516. Object.defineProperties( Store.prototype, prototypeAccessors$1 );
  517. function genericSubscribe (fn, subs, options) {
  518. if (subs.indexOf(fn) < 0) {
  519. options && options.prepend
  520. ? subs.unshift(fn)
  521. : subs.push(fn);
  522. }
  523. return function () {
  524. var i = subs.indexOf(fn);
  525. if (i > -1) {
  526. subs.splice(i, 1);
  527. }
  528. }
  529. }
  530. function resetStore (store, hot) {
  531. store._actions = Object.create(null);
  532. store._mutations = Object.create(null);
  533. store._wrappedGetters = Object.create(null);
  534. store._modulesNamespaceMap = Object.create(null);
  535. var state = store.state;
  536. // init all modules
  537. installModule(store, state, [], store._modules.root, true);
  538. // reset vm
  539. resetStoreVM(store, state, hot);
  540. }
  541. function resetStoreVM (store, state, hot) {
  542. var oldVm = store._vm;
  543. // bind store public getters
  544. store.getters = {};
  545. // reset local getters cache
  546. store._makeLocalGettersCache = Object.create(null);
  547. var wrappedGetters = store._wrappedGetters;
  548. var computed = {};
  549. forEachValue(wrappedGetters, function (fn, key) {
  550. // use computed to leverage its lazy-caching mechanism
  551. // direct inline function use will lead to closure preserving oldVm.
  552. // using partial to return function with only arguments preserved in closure environment.
  553. computed[key] = partial(fn, store);
  554. Object.defineProperty(store.getters, key, {
  555. get: function () { return store._vm[key]; },
  556. enumerable: true // for local getters
  557. });
  558. });
  559. // use a Vue instance to store the state tree
  560. // suppress warnings just in case the user has added
  561. // some funky global mixins
  562. var silent = Vue.config.silent;
  563. Vue.config.silent = true;
  564. store._vm = new Vue({
  565. data: {
  566. $$state: state
  567. },
  568. computed: computed
  569. });
  570. Vue.config.silent = silent;
  571. // enable strict mode for new vm
  572. if (store.strict) {
  573. enableStrictMode(store);
  574. }
  575. if (oldVm) {
  576. if (hot) {
  577. // dispatch changes in all subscribed watchers
  578. // to force getter re-evaluation for hot reloading.
  579. store._withCommit(function () {
  580. oldVm._data.$$state = null;
  581. });
  582. }
  583. Vue.nextTick(function () { return oldVm.$destroy(); });
  584. }
  585. }
  586. function installModule (store, rootState, path, module, hot) {
  587. var isRoot = !path.length;
  588. var namespace = store._modules.getNamespace(path);
  589. // register in namespace map
  590. if (module.namespaced) {
  591. if (store._modulesNamespaceMap[namespace] && (process.env.NODE_ENV !== 'production')) {
  592. console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
  593. }
  594. store._modulesNamespaceMap[namespace] = module;
  595. }
  596. // set state
  597. if (!isRoot && !hot) {
  598. var parentState = getNestedState(rootState, path.slice(0, -1));
  599. var moduleName = path[path.length - 1];
  600. store._withCommit(function () {
  601. if ((process.env.NODE_ENV !== 'production')) {
  602. if (moduleName in parentState) {
  603. console.warn(
  604. ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
  605. );
  606. }
  607. }
  608. Vue.set(parentState, moduleName, module.state);
  609. });
  610. }
  611. var local = module.context = makeLocalContext(store, namespace, path);
  612. module.forEachMutation(function (mutation, key) {
  613. var namespacedType = namespace + key;
  614. registerMutation(store, namespacedType, mutation, local);
  615. });
  616. module.forEachAction(function (action, key) {
  617. var type = action.root ? key : namespace + key;
  618. var handler = action.handler || action;
  619. registerAction(store, type, handler, local);
  620. });
  621. module.forEachGetter(function (getter, key) {
  622. var namespacedType = namespace + key;
  623. registerGetter(store, namespacedType, getter, local);
  624. });
  625. module.forEachChild(function (child, key) {
  626. installModule(store, rootState, path.concat(key), child, hot);
  627. });
  628. }
  629. /**
  630. * make localized dispatch, commit, getters and state
  631. * if there is no namespace, just use root ones
  632. */
  633. function makeLocalContext (store, namespace, path) {
  634. var noNamespace = namespace === '';
  635. var local = {
  636. dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
  637. var args = unifyObjectStyle(_type, _payload, _options);
  638. var payload = args.payload;
  639. var options = args.options;
  640. var type = args.type;
  641. if (!options || !options.root) {
  642. type = namespace + type;
  643. if ((process.env.NODE_ENV !== 'production') && !store._actions[type]) {
  644. console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
  645. return
  646. }
  647. }
  648. return store.dispatch(type, payload)
  649. },
  650. commit: noNamespace ? store.commit : function (_type, _payload, _options) {
  651. var args = unifyObjectStyle(_type, _payload, _options);
  652. var payload = args.payload;
  653. var options = args.options;
  654. var type = args.type;
  655. if (!options || !options.root) {
  656. type = namespace + type;
  657. if ((process.env.NODE_ENV !== 'production') && !store._mutations[type]) {
  658. console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
  659. return
  660. }
  661. }
  662. store.commit(type, payload, options);
  663. }
  664. };
  665. // getters and state object must be gotten lazily
  666. // because they will be changed by vm update
  667. Object.defineProperties(local, {
  668. getters: {
  669. get: noNamespace
  670. ? function () { return store.getters; }
  671. : function () { return makeLocalGetters(store, namespace); }
  672. },
  673. state: {
  674. get: function () { return getNestedState(store.state, path); }
  675. }
  676. });
  677. return local
  678. }
  679. function makeLocalGetters (store, namespace) {
  680. if (!store._makeLocalGettersCache[namespace]) {
  681. var gettersProxy = {};
  682. var splitPos = namespace.length;
  683. Object.keys(store.getters).forEach(function (type) {
  684. // skip if the target getter is not match this namespace
  685. if (type.slice(0, splitPos) !== namespace) { return }
  686. // extract local getter type
  687. var localType = type.slice(splitPos);
  688. // Add a port to the getters proxy.
  689. // Define as getter property because
  690. // we do not want to evaluate the getters in this time.
  691. Object.defineProperty(gettersProxy, localType, {
  692. get: function () { return store.getters[type]; },
  693. enumerable: true
  694. });
  695. });
  696. store._makeLocalGettersCache[namespace] = gettersProxy;
  697. }
  698. return store._makeLocalGettersCache[namespace]
  699. }
  700. function registerMutation (store, type, handler, local) {
  701. var entry = store._mutations[type] || (store._mutations[type] = []);
  702. entry.push(function wrappedMutationHandler (payload) {
  703. handler.call(store, local.state, payload);
  704. });
  705. }
  706. function registerAction (store, type, handler, local) {
  707. var entry = store._actions[type] || (store._actions[type] = []);
  708. entry.push(function wrappedActionHandler (payload) {
  709. var res = handler.call(store, {
  710. dispatch: local.dispatch,
  711. commit: local.commit,
  712. getters: local.getters,
  713. state: local.state,
  714. rootGetters: store.getters,
  715. rootState: store.state
  716. }, payload);
  717. if (!isPromise(res)) {
  718. res = Promise.resolve(res);
  719. }
  720. if (store._devtoolHook) {
  721. return res.catch(function (err) {
  722. store._devtoolHook.emit('vuex:error', err);
  723. throw err
  724. })
  725. } else {
  726. return res
  727. }
  728. });
  729. }
  730. function registerGetter (store, type, rawGetter, local) {
  731. if (store._wrappedGetters[type]) {
  732. if ((process.env.NODE_ENV !== 'production')) {
  733. console.error(("[vuex] duplicate getter key: " + type));
  734. }
  735. return
  736. }
  737. store._wrappedGetters[type] = function wrappedGetter (store) {
  738. return rawGetter(
  739. local.state, // local state
  740. local.getters, // local getters
  741. store.state, // root state
  742. store.getters // root getters
  743. )
  744. };
  745. }
  746. function enableStrictMode (store) {
  747. store._vm.$watch(function () { return this._data.$$state }, function () {
  748. if ((process.env.NODE_ENV !== 'production')) {
  749. assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
  750. }
  751. }, { deep: true, sync: true });
  752. }
  753. function getNestedState (state, path) {
  754. return path.reduce(function (state, key) { return state[key]; }, state)
  755. }
  756. function unifyObjectStyle (type, payload, options) {
  757. if (isObject(type) && type.type) {
  758. options = payload;
  759. payload = type;
  760. type = type.type;
  761. }
  762. if ((process.env.NODE_ENV !== 'production')) {
  763. assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
  764. }
  765. return { type: type, payload: payload, options: options }
  766. }
  767. function install (_Vue) {
  768. if (Vue && _Vue === Vue) {
  769. if ((process.env.NODE_ENV !== 'production')) {
  770. console.error(
  771. '[vuex] already installed. Vue.use(Vuex) should be called only once.'
  772. );
  773. }
  774. return
  775. }
  776. Vue = _Vue;
  777. applyMixin(Vue);
  778. }
  779. /**
  780. * Reduce the code which written in Vue.js for getting the state.
  781. * @param {String} [namespace] - Module's namespace
  782. * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
  783. * @param {Object}
  784. */
  785. var mapState = normalizeNamespace(function (namespace, states) {
  786. var res = {};
  787. if ((process.env.NODE_ENV !== 'production') && !isValidMap(states)) {
  788. console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
  789. }
  790. normalizeMap(states).forEach(function (ref) {
  791. var key = ref.key;
  792. var val = ref.val;
  793. res[key] = function mappedState () {
  794. var state = this.$store.state;
  795. var getters = this.$store.getters;
  796. if (namespace) {
  797. var module = getModuleByNamespace(this.$store, 'mapState', namespace);
  798. if (!module) {
  799. return
  800. }
  801. state = module.context.state;
  802. getters = module.context.getters;
  803. }
  804. return typeof val === 'function'
  805. ? val.call(this, state, getters)
  806. : state[val]
  807. };
  808. // mark vuex getter for devtools
  809. res[key].vuex = true;
  810. });
  811. return res
  812. });
  813. /**
  814. * Reduce the code which written in Vue.js for committing the mutation
  815. * @param {String} [namespace] - Module's namespace
  816. * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept anthor params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  817. * @return {Object}
  818. */
  819. var mapMutations = normalizeNamespace(function (namespace, mutations) {
  820. var res = {};
  821. if ((process.env.NODE_ENV !== 'production') && !isValidMap(mutations)) {
  822. console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
  823. }
  824. normalizeMap(mutations).forEach(function (ref) {
  825. var key = ref.key;
  826. var val = ref.val;
  827. res[key] = function mappedMutation () {
  828. var args = [], len = arguments.length;
  829. while ( len-- ) args[ len ] = arguments[ len ];
  830. // Get the commit method from store
  831. var commit = this.$store.commit;
  832. if (namespace) {
  833. var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  834. if (!module) {
  835. return
  836. }
  837. commit = module.context.commit;
  838. }
  839. return typeof val === 'function'
  840. ? val.apply(this, [commit].concat(args))
  841. : commit.apply(this.$store, [val].concat(args))
  842. };
  843. });
  844. return res
  845. });
  846. /**
  847. * Reduce the code which written in Vue.js for getting the getters
  848. * @param {String} [namespace] - Module's namespace
  849. * @param {Object|Array} getters
  850. * @return {Object}
  851. */
  852. var mapGetters = normalizeNamespace(function (namespace, getters) {
  853. var res = {};
  854. if ((process.env.NODE_ENV !== 'production') && !isValidMap(getters)) {
  855. console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
  856. }
  857. normalizeMap(getters).forEach(function (ref) {
  858. var key = ref.key;
  859. var val = ref.val;
  860. // The namespace has been mutated by normalizeNamespace
  861. val = namespace + val;
  862. res[key] = function mappedGetter () {
  863. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  864. return
  865. }
  866. if ((process.env.NODE_ENV !== 'production') && !(val in this.$store.getters)) {
  867. console.error(("[vuex] unknown getter: " + val));
  868. return
  869. }
  870. return this.$store.getters[val]
  871. };
  872. // mark vuex getter for devtools
  873. res[key].vuex = true;
  874. });
  875. return res
  876. });
  877. /**
  878. * Reduce the code which written in Vue.js for dispatch the action
  879. * @param {String} [namespace] - Module's namespace
  880. * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  881. * @return {Object}
  882. */
  883. var mapActions = normalizeNamespace(function (namespace, actions) {
  884. var res = {};
  885. if ((process.env.NODE_ENV !== 'production') && !isValidMap(actions)) {
  886. console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
  887. }
  888. normalizeMap(actions).forEach(function (ref) {
  889. var key = ref.key;
  890. var val = ref.val;
  891. res[key] = function mappedAction () {
  892. var args = [], len = arguments.length;
  893. while ( len-- ) args[ len ] = arguments[ len ];
  894. // get dispatch function from store
  895. var dispatch = this.$store.dispatch;
  896. if (namespace) {
  897. var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  898. if (!module) {
  899. return
  900. }
  901. dispatch = module.context.dispatch;
  902. }
  903. return typeof val === 'function'
  904. ? val.apply(this, [dispatch].concat(args))
  905. : dispatch.apply(this.$store, [val].concat(args))
  906. };
  907. });
  908. return res
  909. });
  910. /**
  911. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  912. * @param {String} namespace
  913. * @return {Object}
  914. */
  915. var createNamespacedHelpers = function (namespace) { return ({
  916. mapState: mapState.bind(null, namespace),
  917. mapGetters: mapGetters.bind(null, namespace),
  918. mapMutations: mapMutations.bind(null, namespace),
  919. mapActions: mapActions.bind(null, namespace)
  920. }); };
  921. /**
  922. * Normalize the map
  923. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  924. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  925. * @param {Array|Object} map
  926. * @return {Object}
  927. */
  928. function normalizeMap (map) {
  929. if (!isValidMap(map)) {
  930. return []
  931. }
  932. return Array.isArray(map)
  933. ? map.map(function (key) { return ({ key: key, val: key }); })
  934. : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
  935. }
  936. /**
  937. * Validate whether given map is valid or not
  938. * @param {*} map
  939. * @return {Boolean}
  940. */
  941. function isValidMap (map) {
  942. return Array.isArray(map) || isObject(map)
  943. }
  944. /**
  945. * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
  946. * @param {Function} fn
  947. * @return {Function}
  948. */
  949. function normalizeNamespace (fn) {
  950. return function (namespace, map) {
  951. if (typeof namespace !== 'string') {
  952. map = namespace;
  953. namespace = '';
  954. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  955. namespace += '/';
  956. }
  957. return fn(namespace, map)
  958. }
  959. }
  960. /**
  961. * Search a special module from store by namespace. if module not exist, print error message.
  962. * @param {Object} store
  963. * @param {String} helper
  964. * @param {String} namespace
  965. * @return {Object}
  966. */
  967. function getModuleByNamespace (store, helper, namespace) {
  968. var module = store._modulesNamespaceMap[namespace];
  969. if ((process.env.NODE_ENV !== 'production') && !module) {
  970. console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
  971. }
  972. return module
  973. }
  974. // Credits: borrowed code from fcomb/redux-logger
  975. function createLogger (ref) {
  976. if ( ref === void 0 ) ref = {};
  977. var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true;
  978. var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; };
  979. var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; };
  980. var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; };
  981. var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; };
  982. var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; };
  983. var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true;
  984. var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true;
  985. var logger = ref.logger; if ( logger === void 0 ) logger = console;
  986. return function (store) {
  987. var prevState = deepCopy(store.state);
  988. if (typeof logger === 'undefined') {
  989. return
  990. }
  991. if (logMutations) {
  992. store.subscribe(function (mutation, state) {
  993. var nextState = deepCopy(state);
  994. if (filter(mutation, prevState, nextState)) {
  995. var formattedTime = getFormattedTime();
  996. var formattedMutation = mutationTransformer(mutation);
  997. var message = "mutation " + (mutation.type) + formattedTime;
  998. startMessage(logger, message, collapsed);
  999. logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState));
  1000. logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation);
  1001. logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState));
  1002. endMessage(logger);
  1003. }
  1004. prevState = nextState;
  1005. });
  1006. }
  1007. if (logActions) {
  1008. store.subscribeAction(function (action, state) {
  1009. if (actionFilter(action, state)) {
  1010. var formattedTime = getFormattedTime();
  1011. var formattedAction = actionTransformer(action);
  1012. var message = "action " + (action.type) + formattedTime;
  1013. startMessage(logger, message, collapsed);
  1014. logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
  1015. endMessage(logger);
  1016. }
  1017. });
  1018. }
  1019. }
  1020. }
  1021. function startMessage (logger, message, collapsed) {
  1022. var startMessage = collapsed
  1023. ? logger.groupCollapsed
  1024. : logger.group;
  1025. // render
  1026. try {
  1027. startMessage.call(logger, message);
  1028. } catch (e) {
  1029. logger.log(message);
  1030. }
  1031. }
  1032. function endMessage (logger) {
  1033. try {
  1034. logger.groupEnd();
  1035. } catch (e) {
  1036. logger.log('—— log end ——');
  1037. }
  1038. }
  1039. function getFormattedTime () {
  1040. var time = new Date();
  1041. return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)))
  1042. }
  1043. function repeat (str, times) {
  1044. return (new Array(times + 1)).join(str)
  1045. }
  1046. function pad (num, maxLength) {
  1047. return repeat('0', maxLength - num.toString().length) + num
  1048. }
  1049. var index = {
  1050. Store: Store,
  1051. install: install,
  1052. version: '3.5.1',
  1053. mapState: mapState,
  1054. mapMutations: mapMutations,
  1055. mapGetters: mapGetters,
  1056. mapActions: mapActions,
  1057. createNamespacedHelpers: createNamespacedHelpers,
  1058. createLogger: createLogger
  1059. };
  1060. export default index;
  1061. export { Store, createLogger, createNamespacedHelpers, install, mapActions, mapGetters, mapMutations, mapState };