vuex.cjs.js 30 KB

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