vuex.esm-browser.prod.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /*!
  2. * vuex v4.0.0-beta.2
  3. * (c) 2020 Evan You
  4. * @license MIT
  5. */
  6. import { inject, watch, reactive, computed } from 'vue';
  7. var storeKey = 'store';
  8. function useStore (key) {
  9. if ( key === void 0 ) key = null;
  10. return inject(key !== null ? key : storeKey)
  11. }
  12. var target = typeof window !== 'undefined'
  13. ? window
  14. : typeof global !== 'undefined'
  15. ? global
  16. : {};
  17. var devtoolHook = target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
  18. function devtoolPlugin (store) {
  19. if (!devtoolHook) { return }
  20. store._devtoolHook = devtoolHook;
  21. devtoolHook.emit('vuex:init', store);
  22. devtoolHook.on('vuex:travel-to-state', function (targetState) {
  23. store.replaceState(targetState);
  24. });
  25. store.subscribe(function (mutation, state) {
  26. devtoolHook.emit('vuex:mutation', mutation, state);
  27. }, { prepend: true });
  28. store.subscribeAction(function (action, state) {
  29. devtoolHook.emit('vuex:action', action, state);
  30. }, { prepend: true });
  31. }
  32. /**
  33. * Get the first item that pass the test
  34. * by second argument function
  35. *
  36. * @param {Array} list
  37. * @param {Function} f
  38. * @return {*}
  39. */
  40. /**
  41. * forEach for object
  42. */
  43. function forEachValue (obj, fn) {
  44. Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
  45. }
  46. function isObject (obj) {
  47. return obj !== null && typeof obj === 'object'
  48. }
  49. function isPromise (val) {
  50. return val && typeof val.then === 'function'
  51. }
  52. function assert (condition, msg) {
  53. if (!condition) { throw new Error(("[vuex] " + msg)) }
  54. }
  55. function partial (fn, arg) {
  56. return function () {
  57. return fn(arg)
  58. }
  59. }
  60. // Base data struct for store's module, package with some attribute and method
  61. var Module = function Module (rawModule, runtime) {
  62. this.runtime = runtime;
  63. // Store some children item
  64. this._children = Object.create(null);
  65. // Store the origin module object which passed by programmer
  66. this._rawModule = rawModule;
  67. var rawState = rawModule.state;
  68. // Store the origin module's state
  69. this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
  70. };
  71. var prototypeAccessors = { namespaced: { configurable: true } };
  72. prototypeAccessors.namespaced.get = function () {
  73. return !!this._rawModule.namespaced
  74. };
  75. Module.prototype.addChild = function addChild (key, module) {
  76. this._children[key] = module;
  77. };
  78. Module.prototype.removeChild = function removeChild (key) {
  79. delete this._children[key];
  80. };
  81. Module.prototype.getChild = function getChild (key) {
  82. return this._children[key]
  83. };
  84. Module.prototype.hasChild = function hasChild (key) {
  85. return key in this._children
  86. };
  87. Module.prototype.update = function update (rawModule) {
  88. this._rawModule.namespaced = rawModule.namespaced;
  89. if (rawModule.actions) {
  90. this._rawModule.actions = rawModule.actions;
  91. }
  92. if (rawModule.mutations) {
  93. this._rawModule.mutations = rawModule.mutations;
  94. }
  95. if (rawModule.getters) {
  96. this._rawModule.getters = rawModule.getters;
  97. }
  98. };
  99. Module.prototype.forEachChild = function forEachChild (fn) {
  100. forEachValue(this._children, fn);
  101. };
  102. Module.prototype.forEachGetter = function forEachGetter (fn) {
  103. if (this._rawModule.getters) {
  104. forEachValue(this._rawModule.getters, fn);
  105. }
  106. };
  107. Module.prototype.forEachAction = function forEachAction (fn) {
  108. if (this._rawModule.actions) {
  109. forEachValue(this._rawModule.actions, fn);
  110. }
  111. };
  112. Module.prototype.forEachMutation = function forEachMutation (fn) {
  113. if (this._rawModule.mutations) {
  114. forEachValue(this._rawModule.mutations, fn);
  115. }
  116. };
  117. Object.defineProperties( Module.prototype, prototypeAccessors );
  118. var ModuleCollection = function ModuleCollection (rawRootModule) {
  119. // register root module (Vuex.Store options)
  120. this.register([], rawRootModule, false);
  121. };
  122. ModuleCollection.prototype.get = function get (path) {
  123. return path.reduce(function (module, key) {
  124. return module.getChild(key)
  125. }, this.root)
  126. };
  127. ModuleCollection.prototype.getNamespace = function getNamespace (path) {
  128. var module = this.root;
  129. return path.reduce(function (namespace, key) {
  130. module = module.getChild(key);
  131. return namespace + (module.namespaced ? key + '/' : '')
  132. }, '')
  133. };
  134. ModuleCollection.prototype.update = function update$1 (rawRootModule) {
  135. update([], this.root, rawRootModule);
  136. };
  137. ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
  138. var this$1 = this;
  139. if ( runtime === void 0 ) runtime = true;
  140. var newModule = new Module(rawModule, runtime);
  141. if (path.length === 0) {
  142. this.root = newModule;
  143. } else {
  144. var parent = this.get(path.slice(0, -1));
  145. parent.addChild(path[path.length - 1], newModule);
  146. }
  147. // register nested modules
  148. if (rawModule.modules) {
  149. forEachValue(rawModule.modules, function (rawChildModule, key) {
  150. this$1.register(path.concat(key), rawChildModule, runtime);
  151. });
  152. }
  153. };
  154. ModuleCollection.prototype.unregister = function unregister (path) {
  155. var parent = this.get(path.slice(0, -1));
  156. var key = path[path.length - 1];
  157. if (!parent.getChild(key).runtime) { return }
  158. parent.removeChild(key);
  159. };
  160. ModuleCollection.prototype.isRegistered = function isRegistered (path) {
  161. var parent = this.get(path.slice(0, -1));
  162. var key = path[path.length - 1];
  163. return parent.hasChild(key)
  164. };
  165. function update (path, targetModule, newModule) {
  166. // update target module
  167. targetModule.update(newModule);
  168. // update nested modules
  169. if (newModule.modules) {
  170. for (var key in newModule.modules) {
  171. if (!targetModule.getChild(key)) {
  172. return
  173. }
  174. update(
  175. path.concat(key),
  176. targetModule.getChild(key),
  177. newModule.modules[key]
  178. );
  179. }
  180. }
  181. }
  182. function createStore (options) {
  183. return new Store(options)
  184. }
  185. var Store = function Store (options) {
  186. var this$1 = this;
  187. if ( options === void 0 ) options = {};
  188. if (process.env.NODE_ENV !== 'production') {
  189. assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
  190. assert(this instanceof Store, "store must be called with the new operator.");
  191. }
  192. var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
  193. var strict = options.strict; if ( strict === void 0 ) strict = false;
  194. // store internal state
  195. this._committing = false;
  196. this._actions = Object.create(null);
  197. this._actionSubscribers = [];
  198. this._mutations = Object.create(null);
  199. this._wrappedGetters = Object.create(null);
  200. this._modules = new ModuleCollection(options);
  201. this._modulesNamespaceMap = Object.create(null);
  202. this._subscribers = [];
  203. this._makeLocalGettersCache = Object.create(null);
  204. // bind commit and dispatch to self
  205. var store = this;
  206. var ref = this;
  207. var dispatch = ref.dispatch;
  208. var commit = ref.commit;
  209. this.dispatch = function boundDispatch (type, payload) {
  210. return dispatch.call(store, type, payload)
  211. };
  212. this.commit = function boundCommit (type, payload, options) {
  213. return commit.call(store, type, payload, options)
  214. };
  215. // strict mode
  216. this.strict = strict;
  217. var state = this._modules.root.state;
  218. // init root module.
  219. // this also recursively registers all sub-modules
  220. // and collects all module getters inside this._wrappedGetters
  221. installModule(this, state, [], this._modules.root);
  222. // initialize the store state, which is responsible for the reactivity
  223. // (also registers _wrappedGetters as computed properties)
  224. resetStoreState(this, state);
  225. // apply plugins
  226. plugins.forEach(function (plugin) { return plugin(this$1); });
  227. var useDevtools = options.devtools !== undefined ? options.devtools : /* Vue.config.devtools */ true;
  228. if (useDevtools) {
  229. devtoolPlugin(this);
  230. }
  231. };
  232. var prototypeAccessors$1 = { state: { configurable: true } };
  233. Store.prototype.install = function install (app, injectKey) {
  234. app.provide(injectKey || storeKey, this);
  235. app.config.globalProperties.$store = this;
  236. };
  237. prototypeAccessors$1.state.get = function () {
  238. return this._state.data
  239. };
  240. prototypeAccessors$1.state.set = function (v) {
  241. };
  242. Store.prototype.commit = function commit (_type, _payload, _options) {
  243. var this$1 = this;
  244. // check object-style commit
  245. var ref = unifyObjectStyle(_type, _payload, _options);
  246. var type = ref.type;
  247. var payload = ref.payload;
  248. var mutation = { type: type, payload: payload };
  249. var entry = this._mutations[type];
  250. if (!entry) {
  251. return
  252. }
  253. this._withCommit(function () {
  254. entry.forEach(function commitIterator (handler) {
  255. handler(payload);
  256. });
  257. });
  258. this._subscribers
  259. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  260. .forEach(function (sub) { return sub(mutation, this$1.state); });
  261. };
  262. Store.prototype.dispatch = function dispatch (_type, _payload) {
  263. var this$1 = this;
  264. // check object-style dispatch
  265. var ref = unifyObjectStyle(_type, _payload);
  266. var type = ref.type;
  267. var payload = ref.payload;
  268. var action = { type: type, payload: payload };
  269. var entry = this._actions[type];
  270. if (!entry) {
  271. return
  272. }
  273. try {
  274. this._actionSubscribers
  275. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  276. .filter(function (sub) { return sub.before; })
  277. .forEach(function (sub) { return sub.before(action, this$1.state); });
  278. } catch (e) {
  279. }
  280. var result = entry.length > 1
  281. ? Promise.all(entry.map(function (handler) { return handler(payload); }))
  282. : entry[0](payload);
  283. return new Promise(function (resolve, reject) {
  284. result.then(function (res) {
  285. try {
  286. this$1._actionSubscribers
  287. .filter(function (sub) { return sub.after; })
  288. .forEach(function (sub) { return sub.after(action, this$1.state); });
  289. } catch (e) {
  290. }
  291. resolve(res);
  292. }, function (error) {
  293. try {
  294. this$1._actionSubscribers
  295. .filter(function (sub) { return sub.error; })
  296. .forEach(function (sub) { return sub.error(action, this$1.state, error); });
  297. } catch (e) {
  298. }
  299. reject(error);
  300. });
  301. })
  302. };
  303. Store.prototype.subscribe = function subscribe (fn, options) {
  304. return genericSubscribe(fn, this._subscribers, options)
  305. };
  306. Store.prototype.subscribeAction = function subscribeAction (fn, options) {
  307. var subs = typeof fn === 'function' ? { before: fn } : fn;
  308. return genericSubscribe(subs, this._actionSubscribers, options)
  309. };
  310. Store.prototype.watch = function watch$1 (getter, cb, options) {
  311. var this$1 = this;
  312. return watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options))
  313. };
  314. Store.prototype.replaceState = function replaceState (state) {
  315. var this$1 = this;
  316. this._withCommit(function () {
  317. this$1._state.data = state;
  318. });
  319. };
  320. Store.prototype.registerModule = function registerModule (path, rawModule, options) {
  321. if ( options === void 0 ) options = {};
  322. if (typeof path === 'string') { path = [path]; }
  323. this._modules.register(path, rawModule);
  324. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  325. // reset store to update getters...
  326. resetStoreState(this, this.state);
  327. };
  328. Store.prototype.unregisterModule = function unregisterModule (path) {
  329. var this$1 = this;
  330. if (typeof path === 'string') { path = [path]; }
  331. this._modules.unregister(path);
  332. this._withCommit(function () {
  333. var parentState = getNestedState(this$1.state, path.slice(0, -1));
  334. delete parentState[path[path.length - 1]];
  335. });
  336. resetStore(this);
  337. };
  338. Store.prototype.hasModule = function hasModule (path) {
  339. if (typeof path === 'string') { path = [path]; }
  340. return this._modules.isRegistered(path)
  341. };
  342. Store.prototype.hotUpdate = function hotUpdate (newOptions) {
  343. this._modules.update(newOptions);
  344. resetStore(this, true);
  345. };
  346. Store.prototype._withCommit = function _withCommit (fn) {
  347. var committing = this._committing;
  348. this._committing = true;
  349. fn();
  350. this._committing = committing;
  351. };
  352. Object.defineProperties( Store.prototype, prototypeAccessors$1 );
  353. function genericSubscribe (fn, subs, options) {
  354. if (subs.indexOf(fn) < 0) {
  355. options && options.prepend
  356. ? subs.unshift(fn)
  357. : subs.push(fn);
  358. }
  359. return function () {
  360. var i = subs.indexOf(fn);
  361. if (i > -1) {
  362. subs.splice(i, 1);
  363. }
  364. }
  365. }
  366. function resetStore (store, hot) {
  367. store._actions = Object.create(null);
  368. store._mutations = Object.create(null);
  369. store._wrappedGetters = Object.create(null);
  370. store._modulesNamespaceMap = Object.create(null);
  371. var state = store.state;
  372. // init all modules
  373. installModule(store, state, [], store._modules.root, true);
  374. // reset state
  375. resetStoreState(store, state, hot);
  376. }
  377. function resetStoreState (store, state, hot) {
  378. var oldState = store._state;
  379. // bind store public getters
  380. store.getters = {};
  381. // reset local getters cache
  382. store._makeLocalGettersCache = Object.create(null);
  383. var wrappedGetters = store._wrappedGetters;
  384. var computedObj = {};
  385. forEachValue(wrappedGetters, function (fn, key) {
  386. // use computed to leverage its lazy-caching mechanism
  387. // direct inline function use will lead to closure preserving oldVm.
  388. // using partial to return function with only arguments preserved in closure environment.
  389. computedObj[key] = partial(fn, store);
  390. Object.defineProperty(store.getters, key, {
  391. get: function () { return computed(function () { return computedObj[key](); }).value; },
  392. enumerable: true // for local getters
  393. });
  394. });
  395. store._state = reactive({
  396. data: state
  397. });
  398. // enable strict mode for new state
  399. if (store.strict) {
  400. enableStrictMode(store);
  401. }
  402. if (oldState) {
  403. if (hot) {
  404. // dispatch changes in all subscribed watchers
  405. // to force getter re-evaluation for hot reloading.
  406. store._withCommit(function () {
  407. oldState.data = null;
  408. });
  409. }
  410. }
  411. }
  412. function installModule (store, rootState, path, module, hot) {
  413. var isRoot = !path.length;
  414. var namespace = store._modules.getNamespace(path);
  415. // register in namespace map
  416. if (module.namespaced) {
  417. if (store._modulesNamespaceMap[namespace] && false) {
  418. console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
  419. }
  420. store._modulesNamespaceMap[namespace] = module;
  421. }
  422. // set state
  423. if (!isRoot && !hot) {
  424. var parentState = getNestedState(rootState, path.slice(0, -1));
  425. var moduleName = path[path.length - 1];
  426. store._withCommit(function () {
  427. parentState[moduleName] = module.state;
  428. });
  429. }
  430. var local = module.context = makeLocalContext(store, namespace, path);
  431. module.forEachMutation(function (mutation, key) {
  432. var namespacedType = namespace + key;
  433. registerMutation(store, namespacedType, mutation, local);
  434. });
  435. module.forEachAction(function (action, key) {
  436. var type = action.root ? key : namespace + key;
  437. var handler = action.handler || action;
  438. registerAction(store, type, handler, local);
  439. });
  440. module.forEachGetter(function (getter, key) {
  441. var namespacedType = namespace + key;
  442. registerGetter(store, namespacedType, getter, local);
  443. });
  444. module.forEachChild(function (child, key) {
  445. installModule(store, rootState, path.concat(key), child, hot);
  446. });
  447. }
  448. /**
  449. * make localized dispatch, commit, getters and state
  450. * if there is no namespace, just use root ones
  451. */
  452. function makeLocalContext (store, namespace, path) {
  453. var noNamespace = namespace === '';
  454. var local = {
  455. dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
  456. var args = unifyObjectStyle(_type, _payload, _options);
  457. var payload = args.payload;
  458. var options = args.options;
  459. var type = args.type;
  460. if (!options || !options.root) {
  461. type = namespace + type;
  462. }
  463. return store.dispatch(type, payload)
  464. },
  465. commit: noNamespace ? store.commit : function (_type, _payload, _options) {
  466. var args = unifyObjectStyle(_type, _payload, _options);
  467. var payload = args.payload;
  468. var options = args.options;
  469. var type = args.type;
  470. if (!options || !options.root) {
  471. type = namespace + type;
  472. }
  473. store.commit(type, payload, options);
  474. }
  475. };
  476. // getters and state object must be gotten lazily
  477. // because they will be changed by state update
  478. Object.defineProperties(local, {
  479. getters: {
  480. get: noNamespace
  481. ? function () { return store.getters; }
  482. : function () { return makeLocalGetters(store, namespace); }
  483. },
  484. state: {
  485. get: function () { return getNestedState(store.state, path); }
  486. }
  487. });
  488. return local
  489. }
  490. function makeLocalGetters (store, namespace) {
  491. if (!store._makeLocalGettersCache[namespace]) {
  492. var gettersProxy = {};
  493. var splitPos = namespace.length;
  494. Object.keys(store.getters).forEach(function (type) {
  495. // skip if the target getter is not match this namespace
  496. if (type.slice(0, splitPos) !== namespace) { return }
  497. // extract local getter type
  498. var localType = type.slice(splitPos);
  499. // Add a port to the getters proxy.
  500. // Define as getter property because
  501. // we do not want to evaluate the getters in this time.
  502. Object.defineProperty(gettersProxy, localType, {
  503. get: function () { return store.getters[type]; },
  504. enumerable: true
  505. });
  506. });
  507. store._makeLocalGettersCache[namespace] = gettersProxy;
  508. }
  509. return store._makeLocalGettersCache[namespace]
  510. }
  511. function registerMutation (store, type, handler, local) {
  512. var entry = store._mutations[type] || (store._mutations[type] = []);
  513. entry.push(function wrappedMutationHandler (payload) {
  514. handler.call(store, local.state, payload);
  515. });
  516. }
  517. function registerAction (store, type, handler, local) {
  518. var entry = store._actions[type] || (store._actions[type] = []);
  519. entry.push(function wrappedActionHandler (payload) {
  520. var res = handler.call(store, {
  521. dispatch: local.dispatch,
  522. commit: local.commit,
  523. getters: local.getters,
  524. state: local.state,
  525. rootGetters: store.getters,
  526. rootState: store.state
  527. }, payload);
  528. if (!isPromise(res)) {
  529. res = Promise.resolve(res);
  530. }
  531. if (store._devtoolHook) {
  532. return res.catch(function (err) {
  533. store._devtoolHook.emit('vuex:error', err);
  534. throw err
  535. })
  536. } else {
  537. return res
  538. }
  539. });
  540. }
  541. function registerGetter (store, type, rawGetter, local) {
  542. if (store._wrappedGetters[type]) {
  543. return
  544. }
  545. store._wrappedGetters[type] = function wrappedGetter (store) {
  546. return rawGetter(
  547. local.state, // local state
  548. local.getters, // local getters
  549. store.state, // root state
  550. store.getters // root getters
  551. )
  552. };
  553. }
  554. function enableStrictMode (store) {
  555. watch(function () { return store._state.data; }, function () {
  556. }, { deep: true, flush: 'sync' });
  557. }
  558. function getNestedState (state, path) {
  559. return path.reduce(function (state, key) { return state[key]; }, state)
  560. }
  561. function unifyObjectStyle (type, payload, options) {
  562. if (isObject(type) && type.type) {
  563. options = payload;
  564. payload = type;
  565. type = type.type;
  566. }
  567. return { type: type, payload: payload, options: options }
  568. }
  569. /**
  570. * Reduce the code which written in Vue.js for getting the state.
  571. * @param {String} [namespace] - Module's namespace
  572. * @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.
  573. * @param {Object}
  574. */
  575. var mapState = normalizeNamespace(function (namespace, states) {
  576. var res = {};
  577. normalizeMap(states).forEach(function (ref) {
  578. var key = ref.key;
  579. var val = ref.val;
  580. res[key] = function mappedState () {
  581. var state = this.$store.state;
  582. var getters = this.$store.getters;
  583. if (namespace) {
  584. var module = getModuleByNamespace(this.$store, 'mapState', namespace);
  585. if (!module) {
  586. return
  587. }
  588. state = module.context.state;
  589. getters = module.context.getters;
  590. }
  591. return typeof val === 'function'
  592. ? val.call(this, state, getters)
  593. : state[val]
  594. };
  595. // mark vuex getter for devtools
  596. res[key].vuex = true;
  597. });
  598. return res
  599. });
  600. /**
  601. * Reduce the code which written in Vue.js for committing the mutation
  602. * @param {String} [namespace] - Module's namespace
  603. * @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.
  604. * @return {Object}
  605. */
  606. var mapMutations = normalizeNamespace(function (namespace, mutations) {
  607. var res = {};
  608. normalizeMap(mutations).forEach(function (ref) {
  609. var key = ref.key;
  610. var val = ref.val;
  611. res[key] = function mappedMutation () {
  612. var args = [], len = arguments.length;
  613. while ( len-- ) args[ len ] = arguments[ len ];
  614. // Get the commit method from store
  615. var commit = this.$store.commit;
  616. if (namespace) {
  617. var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  618. if (!module) {
  619. return
  620. }
  621. commit = module.context.commit;
  622. }
  623. return typeof val === 'function'
  624. ? val.apply(this, [commit].concat(args))
  625. : commit.apply(this.$store, [val].concat(args))
  626. };
  627. });
  628. return res
  629. });
  630. /**
  631. * Reduce the code which written in Vue.js for getting the getters
  632. * @param {String} [namespace] - Module's namespace
  633. * @param {Object|Array} getters
  634. * @return {Object}
  635. */
  636. var mapGetters = normalizeNamespace(function (namespace, getters) {
  637. var res = {};
  638. normalizeMap(getters).forEach(function (ref) {
  639. var key = ref.key;
  640. var val = ref.val;
  641. // The namespace has been mutated by normalizeNamespace
  642. val = namespace + val;
  643. res[key] = function mappedGetter () {
  644. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  645. return
  646. }
  647. return this.$store.getters[val]
  648. };
  649. // mark vuex getter for devtools
  650. res[key].vuex = true;
  651. });
  652. return res
  653. });
  654. /**
  655. * Reduce the code which written in Vue.js for dispatch the action
  656. * @param {String} [namespace] - Module's namespace
  657. * @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.
  658. * @return {Object}
  659. */
  660. var mapActions = normalizeNamespace(function (namespace, actions) {
  661. var res = {};
  662. normalizeMap(actions).forEach(function (ref) {
  663. var key = ref.key;
  664. var val = ref.val;
  665. res[key] = function mappedAction () {
  666. var args = [], len = arguments.length;
  667. while ( len-- ) args[ len ] = arguments[ len ];
  668. // get dispatch function from store
  669. var dispatch = this.$store.dispatch;
  670. if (namespace) {
  671. var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  672. if (!module) {
  673. return
  674. }
  675. dispatch = module.context.dispatch;
  676. }
  677. return typeof val === 'function'
  678. ? val.apply(this, [dispatch].concat(args))
  679. : dispatch.apply(this.$store, [val].concat(args))
  680. };
  681. });
  682. return res
  683. });
  684. /**
  685. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  686. * @param {String} namespace
  687. * @return {Object}
  688. */
  689. var createNamespacedHelpers = function (namespace) { return ({
  690. mapState: mapState.bind(null, namespace),
  691. mapGetters: mapGetters.bind(null, namespace),
  692. mapMutations: mapMutations.bind(null, namespace),
  693. mapActions: mapActions.bind(null, namespace)
  694. }); };
  695. /**
  696. * Normalize the map
  697. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  698. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  699. * @param {Array|Object} map
  700. * @return {Object}
  701. */
  702. function normalizeMap (map) {
  703. if (!isValidMap(map)) {
  704. return []
  705. }
  706. return Array.isArray(map)
  707. ? map.map(function (key) { return ({ key: key, val: key }); })
  708. : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
  709. }
  710. /**
  711. * Validate whether given map is valid or not
  712. * @param {*} map
  713. * @return {Boolean}
  714. */
  715. function isValidMap (map) {
  716. return Array.isArray(map) || isObject(map)
  717. }
  718. /**
  719. * 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.
  720. * @param {Function} fn
  721. * @return {Function}
  722. */
  723. function normalizeNamespace (fn) {
  724. return function (namespace, map) {
  725. if (typeof namespace !== 'string') {
  726. map = namespace;
  727. namespace = '';
  728. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  729. namespace += '/';
  730. }
  731. return fn(namespace, map)
  732. }
  733. }
  734. /**
  735. * Search a special module from store by namespace. if module not exist, print error message.
  736. * @param {Object} store
  737. * @param {String} helper
  738. * @param {String} namespace
  739. * @return {Object}
  740. */
  741. function getModuleByNamespace (store, helper, namespace) {
  742. var module = store._modulesNamespaceMap[namespace];
  743. return module
  744. }
  745. var index = {
  746. version: '4.0.0-beta.2',
  747. createStore: createStore,
  748. Store: Store,
  749. useStore: useStore,
  750. mapState: mapState,
  751. mapMutations: mapMutations,
  752. mapGetters: mapGetters,
  753. mapActions: mapActions,
  754. createNamespacedHelpers: createNamespacedHelpers
  755. };
  756. export default index;
  757. export { Store, createNamespacedHelpers, createStore, mapActions, mapGetters, mapMutations, mapState, useStore };