vuex.common.js 30 KB

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