vuex.esm.js 36 KB

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