vuex.js 29 KB

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