vuex.esm.browser.js 25 KB

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