vuex.js 37 KB

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