vuex.js 33 KB

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