vuex.common.js 32 KB

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