vuex.global.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /*!
  2. * vuex v4.0.0-beta.2
  3. * (c) 2020 Evan You
  4. * @license MIT
  5. */
  6. var Vuex = (function (vue) {
  7. 'use strict';
  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. {
  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. {
  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. {
  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. {
  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. {
  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. options && options.silent
  317. ) {
  318. console.warn(
  319. "[vuex] mutation type: " + type + ". Silent option has been removed. " +
  320. 'Use the filter functionality in the vue-devtools'
  321. );
  322. }
  323. };
  324. Store.prototype.dispatch = function dispatch (_type, _payload) {
  325. var this$1 = this;
  326. // check object-style dispatch
  327. var ref = unifyObjectStyle(_type, _payload);
  328. var type = ref.type;
  329. var payload = ref.payload;
  330. var action = { type: type, payload: payload };
  331. var entry = this._actions[type];
  332. if (!entry) {
  333. {
  334. console.error(("[vuex] unknown action type: " + type));
  335. }
  336. return
  337. }
  338. try {
  339. this._actionSubscribers
  340. .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
  341. .filter(function (sub) { return sub.before; })
  342. .forEach(function (sub) { return sub.before(action, this$1.state); });
  343. } catch (e) {
  344. {
  345. console.warn("[vuex] error in before action subscribers: ");
  346. console.error(e);
  347. }
  348. }
  349. var result = entry.length > 1
  350. ? Promise.all(entry.map(function (handler) { return handler(payload); }))
  351. : entry[0](payload);
  352. return new Promise(function (resolve, reject) {
  353. result.then(function (res) {
  354. try {
  355. this$1._actionSubscribers
  356. .filter(function (sub) { return sub.after; })
  357. .forEach(function (sub) { return sub.after(action, this$1.state); });
  358. } catch (e) {
  359. {
  360. console.warn("[vuex] error in after action subscribers: ");
  361. console.error(e);
  362. }
  363. }
  364. resolve(res);
  365. }, function (error) {
  366. try {
  367. this$1._actionSubscribers
  368. .filter(function (sub) { return sub.error; })
  369. .forEach(function (sub) { return sub.error(action, this$1.state, error); });
  370. } catch (e) {
  371. {
  372. console.warn("[vuex] error in error action subscribers: ");
  373. console.error(e);
  374. }
  375. }
  376. reject(error);
  377. });
  378. })
  379. };
  380. Store.prototype.subscribe = function subscribe (fn, options) {
  381. return genericSubscribe(fn, this._subscribers, options)
  382. };
  383. Store.prototype.subscribeAction = function subscribeAction (fn, options) {
  384. var subs = typeof fn === 'function' ? { before: fn } : fn;
  385. return genericSubscribe(subs, this._actionSubscribers, options)
  386. };
  387. Store.prototype.watch = function watch$1 (getter, cb, options) {
  388. var this$1 = this;
  389. {
  390. assert(typeof getter === 'function', "store.watch only accepts a function.");
  391. }
  392. return vue.watch(function () { return getter(this$1.state, this$1.getters); }, cb, Object.assign({}, options))
  393. };
  394. Store.prototype.replaceState = function replaceState (state) {
  395. var this$1 = this;
  396. this._withCommit(function () {
  397. this$1._state.data = state;
  398. });
  399. };
  400. Store.prototype.registerModule = function registerModule (path, rawModule, options) {
  401. if ( options === void 0 ) options = {};
  402. if (typeof path === 'string') { path = [path]; }
  403. {
  404. assert(Array.isArray(path), "module path must be a string or an Array.");
  405. assert(path.length > 0, 'cannot register the root module by using registerModule.');
  406. }
  407. this._modules.register(path, rawModule);
  408. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  409. // reset store to update getters...
  410. resetStoreState(this, this.state);
  411. };
  412. Store.prototype.unregisterModule = function unregisterModule (path) {
  413. var this$1 = this;
  414. if (typeof path === 'string') { path = [path]; }
  415. {
  416. assert(Array.isArray(path), "module path must be a string or an Array.");
  417. }
  418. this._modules.unregister(path);
  419. this._withCommit(function () {
  420. var parentState = getNestedState(this$1.state, path.slice(0, -1));
  421. delete parentState[path[path.length - 1]];
  422. });
  423. resetStore(this);
  424. };
  425. Store.prototype.hasModule = function hasModule (path) {
  426. if (typeof path === 'string') { path = [path]; }
  427. {
  428. assert(Array.isArray(path), "module path must be a string or an Array.");
  429. }
  430. return this._modules.isRegistered(path)
  431. };
  432. Store.prototype.hotUpdate = function hotUpdate (newOptions) {
  433. this._modules.update(newOptions);
  434. resetStore(this, true);
  435. };
  436. Store.prototype._withCommit = function _withCommit (fn) {
  437. var committing = this._committing;
  438. this._committing = true;
  439. fn();
  440. this._committing = committing;
  441. };
  442. Object.defineProperties( Store.prototype, prototypeAccessors$1 );
  443. function genericSubscribe (fn, subs, options) {
  444. if (subs.indexOf(fn) < 0) {
  445. options && options.prepend
  446. ? subs.unshift(fn)
  447. : subs.push(fn);
  448. }
  449. return function () {
  450. var i = subs.indexOf(fn);
  451. if (i > -1) {
  452. subs.splice(i, 1);
  453. }
  454. }
  455. }
  456. function resetStore (store, hot) {
  457. store._actions = Object.create(null);
  458. store._mutations = Object.create(null);
  459. store._wrappedGetters = Object.create(null);
  460. store._modulesNamespaceMap = Object.create(null);
  461. var state = store.state;
  462. // init all modules
  463. installModule(store, state, [], store._modules.root, true);
  464. // reset state
  465. resetStoreState(store, state, hot);
  466. }
  467. function resetStoreState (store, state, hot) {
  468. var oldState = store._state;
  469. // bind store public getters
  470. store.getters = {};
  471. // reset local getters cache
  472. store._makeLocalGettersCache = Object.create(null);
  473. var wrappedGetters = store._wrappedGetters;
  474. var computedObj = {};
  475. forEachValue(wrappedGetters, function (fn, key) {
  476. // use computed to leverage its lazy-caching mechanism
  477. // direct inline function use will lead to closure preserving oldVm.
  478. // using partial to return function with only arguments preserved in closure environment.
  479. computedObj[key] = partial(fn, store);
  480. Object.defineProperty(store.getters, key, {
  481. get: function () { return vue.computed(function () { return computedObj[key](); }).value; },
  482. enumerable: true // for local getters
  483. });
  484. });
  485. store._state = vue.reactive({
  486. data: state
  487. });
  488. // enable strict mode for new state
  489. if (store.strict) {
  490. enableStrictMode(store);
  491. }
  492. if (oldState) {
  493. if (hot) {
  494. // dispatch changes in all subscribed watchers
  495. // to force getter re-evaluation for hot reloading.
  496. store._withCommit(function () {
  497. oldState.data = null;
  498. });
  499. }
  500. }
  501. }
  502. function installModule (store, rootState, path, module, hot) {
  503. var isRoot = !path.length;
  504. var namespace = store._modules.getNamespace(path);
  505. // register in namespace map
  506. if (module.namespaced) {
  507. if (store._modulesNamespaceMap[namespace] && true) {
  508. console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
  509. }
  510. store._modulesNamespaceMap[namespace] = module;
  511. }
  512. // set state
  513. if (!isRoot && !hot) {
  514. var parentState = getNestedState(rootState, path.slice(0, -1));
  515. var moduleName = path[path.length - 1];
  516. store._withCommit(function () {
  517. {
  518. if (moduleName in parentState) {
  519. console.warn(
  520. ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
  521. );
  522. }
  523. }
  524. parentState[moduleName] = module.state;
  525. });
  526. }
  527. var local = module.context = makeLocalContext(store, namespace, path);
  528. module.forEachMutation(function (mutation, key) {
  529. var namespacedType = namespace + key;
  530. registerMutation(store, namespacedType, mutation, local);
  531. });
  532. module.forEachAction(function (action, key) {
  533. var type = action.root ? key : namespace + key;
  534. var handler = action.handler || action;
  535. registerAction(store, type, handler, local);
  536. });
  537. module.forEachGetter(function (getter, key) {
  538. var namespacedType = namespace + key;
  539. registerGetter(store, namespacedType, getter, local);
  540. });
  541. module.forEachChild(function (child, key) {
  542. installModule(store, rootState, path.concat(key), child, hot);
  543. });
  544. }
  545. /**
  546. * make localized dispatch, commit, getters and state
  547. * if there is no namespace, just use root ones
  548. */
  549. function makeLocalContext (store, namespace, path) {
  550. var noNamespace = namespace === '';
  551. var local = {
  552. dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
  553. var args = unifyObjectStyle(_type, _payload, _options);
  554. var payload = args.payload;
  555. var options = args.options;
  556. var type = args.type;
  557. if (!options || !options.root) {
  558. type = namespace + type;
  559. if ( !store._actions[type]) {
  560. console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
  561. return
  562. }
  563. }
  564. return store.dispatch(type, payload)
  565. },
  566. commit: noNamespace ? store.commit : function (_type, _payload, _options) {
  567. var args = unifyObjectStyle(_type, _payload, _options);
  568. var payload = args.payload;
  569. var options = args.options;
  570. var type = args.type;
  571. if (!options || !options.root) {
  572. type = namespace + type;
  573. if ( !store._mutations[type]) {
  574. console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
  575. return
  576. }
  577. }
  578. store.commit(type, payload, options);
  579. }
  580. };
  581. // getters and state object must be gotten lazily
  582. // because they will be changed by state update
  583. Object.defineProperties(local, {
  584. getters: {
  585. get: noNamespace
  586. ? function () { return store.getters; }
  587. : function () { return makeLocalGetters(store, namespace); }
  588. },
  589. state: {
  590. get: function () { return getNestedState(store.state, path); }
  591. }
  592. });
  593. return local
  594. }
  595. function makeLocalGetters (store, namespace) {
  596. if (!store._makeLocalGettersCache[namespace]) {
  597. var gettersProxy = {};
  598. var splitPos = namespace.length;
  599. Object.keys(store.getters).forEach(function (type) {
  600. // skip if the target getter is not match this namespace
  601. if (type.slice(0, splitPos) !== namespace) { return }
  602. // extract local getter type
  603. var localType = type.slice(splitPos);
  604. // Add a port to the getters proxy.
  605. // Define as getter property because
  606. // we do not want to evaluate the getters in this time.
  607. Object.defineProperty(gettersProxy, localType, {
  608. get: function () { return store.getters[type]; },
  609. enumerable: true
  610. });
  611. });
  612. store._makeLocalGettersCache[namespace] = gettersProxy;
  613. }
  614. return store._makeLocalGettersCache[namespace]
  615. }
  616. function registerMutation (store, type, handler, local) {
  617. var entry = store._mutations[type] || (store._mutations[type] = []);
  618. entry.push(function wrappedMutationHandler (payload) {
  619. handler.call(store, local.state, payload);
  620. });
  621. }
  622. function registerAction (store, type, handler, local) {
  623. var entry = store._actions[type] || (store._actions[type] = []);
  624. entry.push(function wrappedActionHandler (payload) {
  625. var res = handler.call(store, {
  626. dispatch: local.dispatch,
  627. commit: local.commit,
  628. getters: local.getters,
  629. state: local.state,
  630. rootGetters: store.getters,
  631. rootState: store.state
  632. }, payload);
  633. if (!isPromise(res)) {
  634. res = Promise.resolve(res);
  635. }
  636. if (store._devtoolHook) {
  637. return res.catch(function (err) {
  638. store._devtoolHook.emit('vuex:error', err);
  639. throw err
  640. })
  641. } else {
  642. return res
  643. }
  644. });
  645. }
  646. function registerGetter (store, type, rawGetter, local) {
  647. if (store._wrappedGetters[type]) {
  648. {
  649. console.error(("[vuex] duplicate getter key: " + type));
  650. }
  651. return
  652. }
  653. store._wrappedGetters[type] = function wrappedGetter (store) {
  654. return rawGetter(
  655. local.state, // local state
  656. local.getters, // local getters
  657. store.state, // root state
  658. store.getters // root getters
  659. )
  660. };
  661. }
  662. function enableStrictMode (store) {
  663. vue.watch(function () { return store._state.data; }, function () {
  664. {
  665. assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
  666. }
  667. }, { deep: true, flush: 'sync' });
  668. }
  669. function getNestedState (state, path) {
  670. return path.reduce(function (state, key) { return state[key]; }, state)
  671. }
  672. function unifyObjectStyle (type, payload, options) {
  673. if (isObject(type) && type.type) {
  674. options = payload;
  675. payload = type;
  676. type = type.type;
  677. }
  678. {
  679. assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
  680. }
  681. return { type: type, payload: payload, options: options }
  682. }
  683. /**
  684. * Reduce the code which written in Vue.js for getting the state.
  685. * @param {String} [namespace] - Module's namespace
  686. * @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.
  687. * @param {Object}
  688. */
  689. var mapState = normalizeNamespace(function (namespace, states) {
  690. var res = {};
  691. if ( !isValidMap(states)) {
  692. console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
  693. }
  694. normalizeMap(states).forEach(function (ref) {
  695. var key = ref.key;
  696. var val = ref.val;
  697. res[key] = function mappedState () {
  698. var state = this.$store.state;
  699. var getters = this.$store.getters;
  700. if (namespace) {
  701. var module = getModuleByNamespace(this.$store, 'mapState', namespace);
  702. if (!module) {
  703. return
  704. }
  705. state = module.context.state;
  706. getters = module.context.getters;
  707. }
  708. return typeof val === 'function'
  709. ? val.call(this, state, getters)
  710. : state[val]
  711. };
  712. // mark vuex getter for devtools
  713. res[key].vuex = true;
  714. });
  715. return res
  716. });
  717. /**
  718. * Reduce the code which written in Vue.js for committing the mutation
  719. * @param {String} [namespace] - Module's namespace
  720. * @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.
  721. * @return {Object}
  722. */
  723. var mapMutations = normalizeNamespace(function (namespace, mutations) {
  724. var res = {};
  725. if ( !isValidMap(mutations)) {
  726. console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
  727. }
  728. normalizeMap(mutations).forEach(function (ref) {
  729. var key = ref.key;
  730. var val = ref.val;
  731. res[key] = function mappedMutation () {
  732. var args = [], len = arguments.length;
  733. while ( len-- ) args[ len ] = arguments[ len ];
  734. // Get the commit method from store
  735. var commit = this.$store.commit;
  736. if (namespace) {
  737. var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  738. if (!module) {
  739. return
  740. }
  741. commit = module.context.commit;
  742. }
  743. return typeof val === 'function'
  744. ? val.apply(this, [commit].concat(args))
  745. : commit.apply(this.$store, [val].concat(args))
  746. };
  747. });
  748. return res
  749. });
  750. /**
  751. * Reduce the code which written in Vue.js for getting the getters
  752. * @param {String} [namespace] - Module's namespace
  753. * @param {Object|Array} getters
  754. * @return {Object}
  755. */
  756. var mapGetters = normalizeNamespace(function (namespace, getters) {
  757. var res = {};
  758. if ( !isValidMap(getters)) {
  759. console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
  760. }
  761. normalizeMap(getters).forEach(function (ref) {
  762. var key = ref.key;
  763. var val = ref.val;
  764. // The namespace has been mutated by normalizeNamespace
  765. val = namespace + val;
  766. res[key] = function mappedGetter () {
  767. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  768. return
  769. }
  770. if ( !(val in this.$store.getters)) {
  771. console.error(("[vuex] unknown getter: " + val));
  772. return
  773. }
  774. return this.$store.getters[val]
  775. };
  776. // mark vuex getter for devtools
  777. res[key].vuex = true;
  778. });
  779. return res
  780. });
  781. /**
  782. * Reduce the code which written in Vue.js for dispatch the action
  783. * @param {String} [namespace] - Module's namespace
  784. * @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.
  785. * @return {Object}
  786. */
  787. var mapActions = normalizeNamespace(function (namespace, actions) {
  788. var res = {};
  789. if ( !isValidMap(actions)) {
  790. console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
  791. }
  792. normalizeMap(actions).forEach(function (ref) {
  793. var key = ref.key;
  794. var val = ref.val;
  795. res[key] = function mappedAction () {
  796. var args = [], len = arguments.length;
  797. while ( len-- ) args[ len ] = arguments[ len ];
  798. // get dispatch function from store
  799. var dispatch = this.$store.dispatch;
  800. if (namespace) {
  801. var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  802. if (!module) {
  803. return
  804. }
  805. dispatch = module.context.dispatch;
  806. }
  807. return typeof val === 'function'
  808. ? val.apply(this, [dispatch].concat(args))
  809. : dispatch.apply(this.$store, [val].concat(args))
  810. };
  811. });
  812. return res
  813. });
  814. /**
  815. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  816. * @param {String} namespace
  817. * @return {Object}
  818. */
  819. var createNamespacedHelpers = function (namespace) { return ({
  820. mapState: mapState.bind(null, namespace),
  821. mapGetters: mapGetters.bind(null, namespace),
  822. mapMutations: mapMutations.bind(null, namespace),
  823. mapActions: mapActions.bind(null, namespace)
  824. }); };
  825. /**
  826. * Normalize the map
  827. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  828. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  829. * @param {Array|Object} map
  830. * @return {Object}
  831. */
  832. function normalizeMap (map) {
  833. if (!isValidMap(map)) {
  834. return []
  835. }
  836. return Array.isArray(map)
  837. ? map.map(function (key) { return ({ key: key, val: key }); })
  838. : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
  839. }
  840. /**
  841. * Validate whether given map is valid or not
  842. * @param {*} map
  843. * @return {Boolean}
  844. */
  845. function isValidMap (map) {
  846. return Array.isArray(map) || isObject(map)
  847. }
  848. /**
  849. * 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.
  850. * @param {Function} fn
  851. * @return {Function}
  852. */
  853. function normalizeNamespace (fn) {
  854. return function (namespace, map) {
  855. if (typeof namespace !== 'string') {
  856. map = namespace;
  857. namespace = '';
  858. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  859. namespace += '/';
  860. }
  861. return fn(namespace, map)
  862. }
  863. }
  864. /**
  865. * Search a special module from store by namespace. if module not exist, print error message.
  866. * @param {Object} store
  867. * @param {String} helper
  868. * @param {String} namespace
  869. * @return {Object}
  870. */
  871. function getModuleByNamespace (store, helper, namespace) {
  872. var module = store._modulesNamespaceMap[namespace];
  873. if ( !module) {
  874. console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
  875. }
  876. return module
  877. }
  878. var index_cjs = {
  879. version: '4.0.0-beta.2',
  880. createStore: createStore,
  881. Store: Store,
  882. useStore: useStore,
  883. mapState: mapState,
  884. mapMutations: mapMutations,
  885. mapGetters: mapGetters,
  886. mapActions: mapActions,
  887. createNamespacedHelpers: createNamespacedHelpers
  888. };
  889. return index_cjs;
  890. }(Vue));