vuex.js 31 KB

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