vuex.common.js 28 KB

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