vuex.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /**
  2. * vuex v3.1.1
  3. * (c) 2019 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 = 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. });
  58. }
  59. /**
  60. * Get the first item that pass the test
  61. * by second argument function
  62. *
  63. * @param {Array} list
  64. * @param {Function} f
  65. * @return {*}
  66. */
  67. /**
  68. * forEach for object
  69. */
  70. function forEachValue (obj, fn) {
  71. Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
  72. }
  73. function isObject (obj) {
  74. return obj !== null && typeof obj === 'object'
  75. }
  76. function isPromise (val) {
  77. return val && typeof val.then === 'function'
  78. }
  79. function assert (condition, msg) {
  80. if (!condition) { throw new Error(("[vuex] " + msg)) }
  81. }
  82. function partial (fn, arg) {
  83. return function () {
  84. return fn(arg)
  85. }
  86. }
  87. // Base data struct for store's module, package with some attribute and method
  88. var Module = function Module (rawModule, runtime) {
  89. this.runtime = runtime;
  90. // Store some children item
  91. this._children = Object.create(null);
  92. // Store the origin module object which passed by programmer
  93. this._rawModule = rawModule;
  94. var rawState = rawModule.state;
  95. // Store the origin module's state
  96. this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
  97. };
  98. var prototypeAccessors = { namespaced: { configurable: true } };
  99. prototypeAccessors.namespaced.get = function () {
  100. return !!this._rawModule.namespaced
  101. };
  102. Module.prototype.addChild = function addChild (key, module) {
  103. this._children[key] = module;
  104. };
  105. Module.prototype.removeChild = function removeChild (key) {
  106. delete this._children[key];
  107. };
  108. Module.prototype.getChild = function getChild (key) {
  109. return this._children[key]
  110. };
  111. Module.prototype.update = function update (rawModule) {
  112. this._rawModule.namespaced = rawModule.namespaced;
  113. if (rawModule.actions) {
  114. this._rawModule.actions = rawModule.actions;
  115. }
  116. if (rawModule.mutations) {
  117. this._rawModule.mutations = rawModule.mutations;
  118. }
  119. if (rawModule.getters) {
  120. this._rawModule.getters = rawModule.getters;
  121. }
  122. };
  123. Module.prototype.forEachChild = function forEachChild (fn) {
  124. forEachValue(this._children, fn);
  125. };
  126. Module.prototype.forEachGetter = function forEachGetter (fn) {
  127. if (this._rawModule.getters) {
  128. forEachValue(this._rawModule.getters, fn);
  129. }
  130. };
  131. Module.prototype.forEachAction = function forEachAction (fn) {
  132. if (this._rawModule.actions) {
  133. forEachValue(this._rawModule.actions, fn);
  134. }
  135. };
  136. Module.prototype.forEachMutation = function forEachMutation (fn) {
  137. if (this._rawModule.mutations) {
  138. forEachValue(this._rawModule.mutations, fn);
  139. }
  140. };
  141. Object.defineProperties( Module.prototype, prototypeAccessors );
  142. var ModuleCollection = function ModuleCollection (rawRootModule) {
  143. // register root module (Vuex.Store options)
  144. this.register([], rawRootModule, false);
  145. };
  146. ModuleCollection.prototype.get = function get (path) {
  147. return path.reduce(function (module, key) {
  148. return module.getChild(key)
  149. }, this.root)
  150. };
  151. ModuleCollection.prototype.getNamespace = function getNamespace (path) {
  152. var module = this.root;
  153. return path.reduce(function (namespace, key) {
  154. module = module.getChild(key);
  155. return namespace + (module.namespaced ? key + '/' : '')
  156. }, '')
  157. };
  158. ModuleCollection.prototype.update = function update$1 (rawRootModule) {
  159. update([], this.root, rawRootModule);
  160. };
  161. ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
  162. var this$1 = this;
  163. if ( runtime === void 0 ) runtime = true;
  164. {
  165. assertRawModule(path, rawModule);
  166. }
  167. var newModule = new Module(rawModule, runtime);
  168. if (path.length === 0) {
  169. this.root = newModule;
  170. } else {
  171. var parent = this.get(path.slice(0, -1));
  172. parent.addChild(path[path.length - 1], newModule);
  173. }
  174. // register nested modules
  175. if (rawModule.modules) {
  176. forEachValue(rawModule.modules, function (rawChildModule, key) {
  177. this$1.register(path.concat(key), rawChildModule, runtime);
  178. });
  179. }
  180. };
  181. ModuleCollection.prototype.unregister = function unregister (path) {
  182. var parent = this.get(path.slice(0, -1));
  183. var key = path[path.length - 1];
  184. if (!parent.getChild(key).runtime) { return }
  185. parent.removeChild(key);
  186. };
  187. function update (path, targetModule, newModule) {
  188. {
  189. assertRawModule(path, newModule);
  190. }
  191. // update target module
  192. targetModule.update(newModule);
  193. // update nested modules
  194. if (newModule.modules) {
  195. for (var key in newModule.modules) {
  196. if (!targetModule.getChild(key)) {
  197. {
  198. console.warn(
  199. "[vuex] trying to add a new module '" + key + "' on hot reloading, " +
  200. 'manual reload is needed'
  201. );
  202. }
  203. return
  204. }
  205. update(
  206. path.concat(key),
  207. targetModule.getChild(key),
  208. newModule.modules[key]
  209. );
  210. }
  211. }
  212. }
  213. var functionAssert = {
  214. assert: function (value) { return typeof value === 'function'; },
  215. expected: 'function'
  216. };
  217. var objectAssert = {
  218. assert: function (value) { return typeof value === 'function' ||
  219. (typeof value === 'object' && typeof value.handler === 'function'); },
  220. expected: 'function or object with "handler" function'
  221. };
  222. var assertTypes = {
  223. getters: functionAssert,
  224. mutations: functionAssert,
  225. actions: objectAssert
  226. };
  227. function assertRawModule (path, rawModule) {
  228. Object.keys(assertTypes).forEach(function (key) {
  229. if (!rawModule[key]) { return }
  230. var assertOptions = assertTypes[key];
  231. forEachValue(rawModule[key], function (value, type) {
  232. assert(
  233. assertOptions.assert(value),
  234. makeAssertionMessage(path, key, type, value, assertOptions.expected)
  235. );
  236. });
  237. });
  238. }
  239. function makeAssertionMessage (path, key, type, value, expected) {
  240. var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
  241. if (path.length > 0) {
  242. buf += " in module \"" + (path.join('.')) + "\"";
  243. }
  244. buf += " is " + (JSON.stringify(value)) + ".";
  245. return buf
  246. }
  247. var Vue; // bind on install
  248. var Store = function Store (options) {
  249. var this$1 = this;
  250. if ( options === void 0 ) options = {};
  251. // Auto install if it is not done yet and `window` has `Vue`.
  252. // To allow users to avoid auto-installation in some cases,
  253. // this code should be placed here. See #731
  254. if (!Vue && typeof window !== 'undefined' && window.Vue) {
  255. install(window.Vue);
  256. }
  257. {
  258. assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
  259. assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
  260. assert(this instanceof Store, "store must be called with the new operator.");
  261. }
  262. var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
  263. var strict = options.strict; if ( strict === void 0 ) strict = false;
  264. // store internal state
  265. this._committing = false;
  266. this._actions = Object.create(null);
  267. this._actionSubscribers = [];
  268. this._mutations = Object.create(null);
  269. this._wrappedGetters = Object.create(null);
  270. this._modules = new ModuleCollection(options);
  271. this._modulesNamespaceMap = Object.create(null);
  272. this._subscribers = [];
  273. this._watcherVM = new Vue();
  274. // bind commit and dispatch to self
  275. var store = this;
  276. var ref = this;
  277. var dispatch = ref.dispatch;
  278. var commit = ref.commit;
  279. this.dispatch = function boundDispatch (type, payload) {
  280. return dispatch.call(store, type, payload)
  281. };
  282. this.commit = function boundCommit (type, payload, options) {
  283. return commit.call(store, type, payload, options)
  284. };
  285. // strict mode
  286. this.strict = strict;
  287. var state = this._modules.root.state;
  288. // init root module.
  289. // this also recursively registers all sub-modules
  290. // and collects all module getters inside this._wrappedGetters
  291. installModule(this, state, [], this._modules.root);
  292. // initialize the store vm, which is responsible for the reactivity
  293. // (also registers _wrappedGetters as computed properties)
  294. resetStoreVM(this, state);
  295. // apply plugins
  296. plugins.forEach(function (plugin) { return plugin(this$1); });
  297. var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
  298. if (useDevtools) {
  299. devtoolPlugin(this);
  300. }
  301. };
  302. var prototypeAccessors$1 = { state: { configurable: true } };
  303. prototypeAccessors$1.state.get = function () {
  304. return this._vm._data.$$state
  305. };
  306. prototypeAccessors$1.state.set = function (v) {
  307. {
  308. assert(false, "use store.replaceState() to explicit replace store state.");
  309. }
  310. };
  311. Store.prototype.commit = function commit (_type, _payload, _options) {
  312. var this$1 = this;
  313. // check object-style commit
  314. var ref = unifyObjectStyle(_type, _payload, _options);
  315. var type = ref.type;
  316. var payload = ref.payload;
  317. var options = ref.options;
  318. var mutation = { type: type, payload: payload };
  319. var entry = this._mutations[type];
  320. if (!entry) {
  321. {
  322. console.error(("[vuex] unknown mutation type: " + type));
  323. }
  324. return
  325. }
  326. this._withCommit(function () {
  327. entry.forEach(function commitIterator (handler) {
  328. handler(payload);
  329. });
  330. });
  331. this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); });
  332. if (
  333. options && options.silent
  334. ) {
  335. console.warn(
  336. "[vuex] mutation type: " + type + ". Silent option has been removed. " +
  337. 'Use the filter functionality in the vue-devtools'
  338. );
  339. }
  340. };
  341. Store.prototype.dispatch = function dispatch (_type, _payload) {
  342. var this$1 = this;
  343. // check object-style dispatch
  344. var ref = unifyObjectStyle(_type, _payload);
  345. var type = ref.type;
  346. var payload = ref.payload;
  347. var action = { type: type, payload: payload };
  348. var entry = this._actions[type];
  349. if (!entry) {
  350. {
  351. console.error(("[vuex] unknown action type: " + type));
  352. }
  353. return
  354. }
  355. try {
  356. this._actionSubscribers
  357. .filter(function (sub) { return sub.before; })
  358. .forEach(function (sub) { return sub.before(action, this$1.state); });
  359. } catch (e) {
  360. {
  361. console.warn("[vuex] error in before action subscribers: ");
  362. console.error(e);
  363. }
  364. }
  365. var result = entry.length > 1
  366. ? Promise.all(entry.map(function (handler) { return handler(payload); }))
  367. : entry[0](payload);
  368. return result.then(function (res) {
  369. try {
  370. this$1._actionSubscribers
  371. .filter(function (sub) { return sub.after; })
  372. .forEach(function (sub) { return sub.after(action, this$1.state); });
  373. } catch (e) {
  374. {
  375. console.warn("[vuex] error in after action subscribers: ");
  376. console.error(e);
  377. }
  378. }
  379. return res
  380. })
  381. };
  382. Store.prototype.subscribe = function subscribe (fn) {
  383. return genericSubscribe(fn, this._subscribers)
  384. };
  385. Store.prototype.subscribeAction = function subscribeAction (fn) {
  386. var subs = typeof fn === 'function' ? { before: fn } : fn;
  387. return genericSubscribe(subs, this._actionSubscribers)
  388. };
  389. Store.prototype.watch = function watch (getter, cb, options) {
  390. var this$1 = this;
  391. {
  392. assert(typeof getter === 'function', "store.watch only accepts a function.");
  393. }
  394. return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
  395. };
  396. Store.prototype.replaceState = function replaceState (state) {
  397. var this$1 = this;
  398. this._withCommit(function () {
  399. this$1._vm._data.$$state = state;
  400. });
  401. };
  402. Store.prototype.registerModule = function registerModule (path, rawModule, options) {
  403. if ( options === void 0 ) options = {};
  404. if (typeof path === 'string') { path = [path]; }
  405. {
  406. assert(Array.isArray(path), "module path must be a string or an Array.");
  407. assert(path.length > 0, 'cannot register the root module by using registerModule.');
  408. }
  409. this._modules.register(path, rawModule);
  410. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  411. // reset store to update getters...
  412. resetStoreVM(this, this.state);
  413. };
  414. Store.prototype.unregisterModule = function unregisterModule (path) {
  415. var this$1 = this;
  416. if (typeof path === 'string') { path = [path]; }
  417. {
  418. assert(Array.isArray(path), "module path must be a string or an Array.");
  419. }
  420. this._modules.unregister(path);
  421. this._withCommit(function () {
  422. var parentState = getNestedState(this$1.state, path.slice(0, -1));
  423. Vue.delete(parentState, path[path.length - 1]);
  424. });
  425. resetStore(this);
  426. };
  427. Store.prototype.hotUpdate = function hotUpdate (newOptions) {
  428. this._modules.update(newOptions);
  429. resetStore(this, true);
  430. };
  431. Store.prototype._withCommit = function _withCommit (fn) {
  432. var committing = this._committing;
  433. this._committing = true;
  434. fn();
  435. this._committing = committing;
  436. };
  437. Object.defineProperties( Store.prototype, prototypeAccessors$1 );
  438. function genericSubscribe (fn, subs) {
  439. if (subs.indexOf(fn) < 0) {
  440. subs.push(fn);
  441. }
  442. return function () {
  443. var i = subs.indexOf(fn);
  444. if (i > -1) {
  445. subs.splice(i, 1);
  446. }
  447. }
  448. }
  449. function resetStore (store, hot) {
  450. store._actions = Object.create(null);
  451. store._mutations = Object.create(null);
  452. store._wrappedGetters = Object.create(null);
  453. store._modulesNamespaceMap = Object.create(null);
  454. var state = store.state;
  455. // init all modules
  456. installModule(store, state, [], store._modules.root, true);
  457. // reset vm
  458. resetStoreVM(store, state, hot);
  459. }
  460. function resetStoreVM (store, state, hot) {
  461. var oldVm = store._vm;
  462. // bind store public getters
  463. store.getters = {};
  464. var wrappedGetters = store._wrappedGetters;
  465. var computed = {};
  466. forEachValue(wrappedGetters, function (fn, key) {
  467. // use computed to leverage its lazy-caching mechanism
  468. // direct inline function use will lead to closure preserving oldVm.
  469. // using partial to return function with only arguments preserved in closure enviroment.
  470. computed[key] = partial(fn, store);
  471. Object.defineProperty(store.getters, key, {
  472. get: function () { return store._vm[key]; },
  473. enumerable: true // for local getters
  474. });
  475. });
  476. // use a Vue instance to store the state tree
  477. // suppress warnings just in case the user has added
  478. // some funky global mixins
  479. var silent = Vue.config.silent;
  480. Vue.config.silent = true;
  481. store._vm = new Vue({
  482. data: {
  483. $$state: state
  484. },
  485. computed: computed
  486. });
  487. Vue.config.silent = silent;
  488. // enable strict mode for new vm
  489. if (store.strict) {
  490. enableStrictMode(store);
  491. }
  492. if (oldVm) {
  493. if (hot) {
  494. // dispatch changes in all subscribed watchers
  495. // to force getter re-evaluation for hot reloading.
  496. store._withCommit(function () {
  497. oldVm._data.$$state = null;
  498. });
  499. }
  500. Vue.nextTick(function () { return oldVm.$destroy(); });
  501. }
  502. }
  503. function installModule (store, rootState, path, module, hot) {
  504. var isRoot = !path.length;
  505. var namespace = store._modules.getNamespace(path);
  506. // register in namespace map
  507. if (module.namespaced) {
  508. store._modulesNamespaceMap[namespace] = module;
  509. }
  510. // set state
  511. if (!isRoot && !hot) {
  512. var parentState = getNestedState(rootState, path.slice(0, -1));
  513. var moduleName = path[path.length - 1];
  514. store._withCommit(function () {
  515. Vue.set(parentState, moduleName, module.state);
  516. });
  517. }
  518. var local = module.context = makeLocalContext(store, namespace, path);
  519. module.forEachMutation(function (mutation, key) {
  520. var namespacedType = namespace + key;
  521. registerMutation(store, namespacedType, mutation, local);
  522. });
  523. module.forEachAction(function (action, key) {
  524. var type = action.root ? key : namespace + key;
  525. var handler = action.handler || action;
  526. registerAction(store, type, handler, local);
  527. });
  528. module.forEachGetter(function (getter, key) {
  529. var namespacedType = namespace + key;
  530. registerGetter(store, namespacedType, getter, local);
  531. });
  532. module.forEachChild(function (child, key) {
  533. installModule(store, rootState, path.concat(key), child, hot);
  534. });
  535. }
  536. /**
  537. * make localized dispatch, commit, getters and state
  538. * if there is no namespace, just use root ones
  539. */
  540. function makeLocalContext (store, namespace, path) {
  541. var noNamespace = namespace === '';
  542. var local = {
  543. dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
  544. var args = unifyObjectStyle(_type, _payload, _options);
  545. var payload = args.payload;
  546. var options = args.options;
  547. var type = args.type;
  548. if (!options || !options.root) {
  549. type = namespace + type;
  550. if (!store._actions[type]) {
  551. console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
  552. return
  553. }
  554. }
  555. return store.dispatch(type, payload)
  556. },
  557. commit: noNamespace ? store.commit : function (_type, _payload, _options) {
  558. var args = unifyObjectStyle(_type, _payload, _options);
  559. var payload = args.payload;
  560. var options = args.options;
  561. var type = args.type;
  562. if (!options || !options.root) {
  563. type = namespace + type;
  564. if (!store._mutations[type]) {
  565. console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
  566. return
  567. }
  568. }
  569. store.commit(type, payload, options);
  570. }
  571. };
  572. // getters and state object must be gotten lazily
  573. // because they will be changed by vm update
  574. Object.defineProperties(local, {
  575. getters: {
  576. get: noNamespace
  577. ? function () { return store.getters; }
  578. : function () { return makeLocalGetters(store, namespace); }
  579. },
  580. state: {
  581. get: function () { return getNestedState(store.state, path); }
  582. }
  583. });
  584. return local
  585. }
  586. function makeLocalGetters (store, namespace) {
  587. var gettersProxy = {};
  588. var splitPos = namespace.length;
  589. Object.keys(store.getters).forEach(function (type) {
  590. // skip if the target getter is not match this namespace
  591. if (type.slice(0, splitPos) !== namespace) { return }
  592. // extract local getter type
  593. var localType = type.slice(splitPos);
  594. // Add a port to the getters proxy.
  595. // Define as getter property because
  596. // we do not want to evaluate the getters in this time.
  597. Object.defineProperty(gettersProxy, localType, {
  598. get: function () { return store.getters[type]; },
  599. enumerable: true
  600. });
  601. });
  602. return gettersProxy
  603. }
  604. function registerMutation (store, type, handler, local) {
  605. var entry = store._mutations[type] || (store._mutations[type] = []);
  606. entry.push(function wrappedMutationHandler (payload) {
  607. handler.call(store, local.state, payload);
  608. });
  609. }
  610. function registerAction (store, type, handler, local) {
  611. var entry = store._actions[type] || (store._actions[type] = []);
  612. entry.push(function wrappedActionHandler (payload, cb) {
  613. var res = handler.call(store, {
  614. dispatch: local.dispatch,
  615. commit: local.commit,
  616. getters: local.getters,
  617. state: local.state,
  618. rootGetters: store.getters,
  619. rootState: store.state
  620. }, payload, cb);
  621. if (!isPromise(res)) {
  622. res = Promise.resolve(res);
  623. }
  624. if (store._devtoolHook) {
  625. return res.catch(function (err) {
  626. store._devtoolHook.emit('vuex:error', err);
  627. throw err
  628. })
  629. } else {
  630. return res
  631. }
  632. });
  633. }
  634. function registerGetter (store, type, rawGetter, local) {
  635. if (store._wrappedGetters[type]) {
  636. {
  637. console.error(("[vuex] duplicate getter key: " + type));
  638. }
  639. return
  640. }
  641. store._wrappedGetters[type] = function wrappedGetter (store) {
  642. return rawGetter(
  643. local.state, // local state
  644. local.getters, // local getters
  645. store.state, // root state
  646. store.getters // root getters
  647. )
  648. };
  649. }
  650. function enableStrictMode (store) {
  651. store._vm.$watch(function () { return this._data.$$state }, function () {
  652. {
  653. assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
  654. }
  655. }, { deep: true, sync: true });
  656. }
  657. function getNestedState (state, path) {
  658. return path.length
  659. ? path.reduce(function (state, key) { return state[key]; }, state)
  660. : state
  661. }
  662. function unifyObjectStyle (type, payload, options) {
  663. if (isObject(type) && type.type) {
  664. options = payload;
  665. payload = type;
  666. type = type.type;
  667. }
  668. {
  669. assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
  670. }
  671. return { type: type, payload: payload, options: options }
  672. }
  673. function install (_Vue) {
  674. if (Vue && _Vue === Vue) {
  675. {
  676. console.error(
  677. '[vuex] already installed. Vue.use(Vuex) should be called only once.'
  678. );
  679. }
  680. return
  681. }
  682. Vue = _Vue;
  683. applyMixin(Vue);
  684. }
  685. /**
  686. * Reduce the code which written in Vue.js for getting the state.
  687. * @param {String} [namespace] - Module's namespace
  688. * @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.
  689. * @param {Object}
  690. */
  691. var mapState = normalizeNamespace(function (namespace, states) {
  692. var res = {};
  693. normalizeMap(states).forEach(function (ref) {
  694. var key = ref.key;
  695. var val = ref.val;
  696. res[key] = function mappedState () {
  697. var state = this.$store.state;
  698. var getters = this.$store.getters;
  699. if (namespace) {
  700. var module = getModuleByNamespace(this.$store, 'mapState', namespace);
  701. if (!module) {
  702. return
  703. }
  704. state = module.context.state;
  705. getters = module.context.getters;
  706. }
  707. return typeof val === 'function'
  708. ? val.call(this, state, getters)
  709. : state[val]
  710. };
  711. // mark vuex getter for devtools
  712. res[key].vuex = true;
  713. });
  714. return res
  715. });
  716. /**
  717. * Reduce the code which written in Vue.js for committing the mutation
  718. * @param {String} [namespace] - Module's namespace
  719. * @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.
  720. * @return {Object}
  721. */
  722. var mapMutations = normalizeNamespace(function (namespace, mutations) {
  723. var res = {};
  724. normalizeMap(mutations).forEach(function (ref) {
  725. var key = ref.key;
  726. var val = ref.val;
  727. res[key] = function mappedMutation () {
  728. var args = [], len = arguments.length;
  729. while ( len-- ) args[ len ] = arguments[ len ];
  730. // Get the commit method from store
  731. var commit = this.$store.commit;
  732. if (namespace) {
  733. var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  734. if (!module) {
  735. return
  736. }
  737. commit = module.context.commit;
  738. }
  739. return typeof val === 'function'
  740. ? val.apply(this, [commit].concat(args))
  741. : commit.apply(this.$store, [val].concat(args))
  742. };
  743. });
  744. return res
  745. });
  746. /**
  747. * Reduce the code which written in Vue.js for getting the getters
  748. * @param {String} [namespace] - Module's namespace
  749. * @param {Object|Array} getters
  750. * @return {Object}
  751. */
  752. var mapGetters = normalizeNamespace(function (namespace, getters) {
  753. var res = {};
  754. normalizeMap(getters).forEach(function (ref) {
  755. var key = ref.key;
  756. var val = ref.val;
  757. // The namespace has been mutated by normalizeNamespace
  758. val = namespace + val;
  759. res[key] = function mappedGetter () {
  760. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  761. return
  762. }
  763. if (!(val in this.$store.getters)) {
  764. console.error(("[vuex] unknown getter: " + val));
  765. return
  766. }
  767. return this.$store.getters[val]
  768. };
  769. // mark vuex getter for devtools
  770. res[key].vuex = true;
  771. });
  772. return res
  773. });
  774. /**
  775. * Reduce the code which written in Vue.js for dispatch the action
  776. * @param {String} [namespace] - Module's namespace
  777. * @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.
  778. * @return {Object}
  779. */
  780. var mapActions = normalizeNamespace(function (namespace, actions) {
  781. var res = {};
  782. normalizeMap(actions).forEach(function (ref) {
  783. var key = ref.key;
  784. var val = ref.val;
  785. res[key] = function mappedAction () {
  786. var args = [], len = arguments.length;
  787. while ( len-- ) args[ len ] = arguments[ len ];
  788. // get dispatch function from store
  789. var dispatch = this.$store.dispatch;
  790. if (namespace) {
  791. var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  792. if (!module) {
  793. return
  794. }
  795. dispatch = module.context.dispatch;
  796. }
  797. return typeof val === 'function'
  798. ? val.apply(this, [dispatch].concat(args))
  799. : dispatch.apply(this.$store, [val].concat(args))
  800. };
  801. });
  802. return res
  803. });
  804. /**
  805. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  806. * @param {String} namespace
  807. * @return {Object}
  808. */
  809. var createNamespacedHelpers = function (namespace) { return ({
  810. mapState: mapState.bind(null, namespace),
  811. mapGetters: mapGetters.bind(null, namespace),
  812. mapMutations: mapMutations.bind(null, namespace),
  813. mapActions: mapActions.bind(null, namespace)
  814. }); };
  815. /**
  816. * Normalize the map
  817. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  818. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  819. * @param {Array|Object} map
  820. * @return {Object}
  821. */
  822. function normalizeMap (map) {
  823. return Array.isArray(map)
  824. ? map.map(function (key) { return ({ key: key, val: key }); })
  825. : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
  826. }
  827. /**
  828. * 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.
  829. * @param {Function} fn
  830. * @return {Function}
  831. */
  832. function normalizeNamespace (fn) {
  833. return function (namespace, map) {
  834. if (typeof namespace !== 'string') {
  835. map = namespace;
  836. namespace = '';
  837. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  838. namespace += '/';
  839. }
  840. return fn(namespace, map)
  841. }
  842. }
  843. /**
  844. * Search a special module from store by namespace. if module not exist, print error message.
  845. * @param {Object} store
  846. * @param {String} helper
  847. * @param {String} namespace
  848. * @return {Object}
  849. */
  850. function getModuleByNamespace (store, helper, namespace) {
  851. var module = store._modulesNamespaceMap[namespace];
  852. if (!module) {
  853. console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
  854. }
  855. return module
  856. }
  857. var index = {
  858. Store: Store,
  859. install: install,
  860. version: '3.1.1',
  861. mapState: mapState,
  862. mapMutations: mapMutations,
  863. mapGetters: mapGetters,
  864. mapActions: mapActions,
  865. createNamespacedHelpers: createNamespacedHelpers
  866. };
  867. return index;
  868. }));