vuex.esm-browser.js 29 KB

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