vuex.esm.browser.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. /**
  2. * vuex v3.1.2
  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. this._makeLocalGettersCache = Object.create(null);
  270. // bind commit and dispatch to self
  271. const store = this;
  272. const { dispatch, commit } = this;
  273. this.dispatch = function boundDispatch (type, payload) {
  274. return dispatch.call(store, type, payload)
  275. };
  276. this.commit = function boundCommit (type, payload, options) {
  277. return commit.call(store, type, payload, options)
  278. };
  279. // strict mode
  280. this.strict = strict;
  281. const state = this._modules.root.state;
  282. // init root module.
  283. // this also recursively registers all sub-modules
  284. // and collects all module getters inside this._wrappedGetters
  285. installModule(this, state, [], this._modules.root);
  286. // initialize the store vm, which is responsible for the reactivity
  287. // (also registers _wrappedGetters as computed properties)
  288. resetStoreVM(this, state);
  289. // apply plugins
  290. plugins.forEach(plugin => plugin(this));
  291. const useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
  292. if (useDevtools) {
  293. devtoolPlugin(this);
  294. }
  295. }
  296. get state () {
  297. return this._vm._data.$$state
  298. }
  299. set state (v) {
  300. {
  301. assert(false, `use store.replaceState() to explicit replace store state.`);
  302. }
  303. }
  304. commit (_type, _payload, _options) {
  305. // check object-style commit
  306. const {
  307. type,
  308. payload,
  309. options
  310. } = unifyObjectStyle(_type, _payload, _options);
  311. const mutation = { type, payload };
  312. const entry = this._mutations[type];
  313. if (!entry) {
  314. {
  315. console.error(`[vuex] unknown mutation type: ${type}`);
  316. }
  317. return
  318. }
  319. this._withCommit(() => {
  320. entry.forEach(function commitIterator (handler) {
  321. handler(payload);
  322. });
  323. });
  324. this._subscribers.forEach(sub => sub(mutation, this.state));
  325. if (
  326. options && options.silent
  327. ) {
  328. console.warn(
  329. `[vuex] mutation type: ${type}. Silent option has been removed. ` +
  330. 'Use the filter functionality in the vue-devtools'
  331. );
  332. }
  333. }
  334. dispatch (_type, _payload) {
  335. // check object-style dispatch
  336. const {
  337. type,
  338. payload
  339. } = unifyObjectStyle(_type, _payload);
  340. const action = { type, payload };
  341. const entry = this._actions[type];
  342. if (!entry) {
  343. {
  344. console.error(`[vuex] unknown action type: ${type}`);
  345. }
  346. return
  347. }
  348. try {
  349. this._actionSubscribers
  350. .filter(sub => sub.before)
  351. .forEach(sub => sub.before(action, this.state));
  352. } catch (e) {
  353. {
  354. console.warn(`[vuex] error in before action subscribers: `);
  355. console.error(e);
  356. }
  357. }
  358. const result = entry.length > 1
  359. ? Promise.all(entry.map(handler => handler(payload)))
  360. : entry[0](payload);
  361. return result.then(res => {
  362. try {
  363. this._actionSubscribers
  364. .filter(sub => sub.after)
  365. .forEach(sub => sub.after(action, this.state));
  366. } catch (e) {
  367. {
  368. console.warn(`[vuex] error in after action subscribers: `);
  369. console.error(e);
  370. }
  371. }
  372. return res
  373. })
  374. }
  375. subscribe (fn) {
  376. return genericSubscribe(fn, this._subscribers)
  377. }
  378. subscribeAction (fn) {
  379. const subs = typeof fn === 'function' ? { before: fn } : fn;
  380. return genericSubscribe(subs, this._actionSubscribers)
  381. }
  382. watch (getter, cb, options) {
  383. {
  384. assert(typeof getter === 'function', `store.watch only accepts a function.`);
  385. }
  386. return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options)
  387. }
  388. replaceState (state) {
  389. this._withCommit(() => {
  390. this._vm._data.$$state = state;
  391. });
  392. }
  393. registerModule (path, rawModule, options = {}) {
  394. if (typeof path === 'string') path = [path];
  395. {
  396. assert(Array.isArray(path), `module path must be a string or an Array.`);
  397. assert(path.length > 0, 'cannot register the root module by using registerModule.');
  398. }
  399. this._modules.register(path, rawModule);
  400. installModule(this, this.state, path, this._modules.get(path), options.preserveState);
  401. // reset store to update getters...
  402. resetStoreVM(this, this.state);
  403. }
  404. unregisterModule (path) {
  405. if (typeof path === 'string') path = [path];
  406. {
  407. assert(Array.isArray(path), `module path must be a string or an Array.`);
  408. }
  409. this._modules.unregister(path);
  410. this._withCommit(() => {
  411. const parentState = getNestedState(this.state, path.slice(0, -1));
  412. Vue.delete(parentState, path[path.length - 1]);
  413. });
  414. resetStore(this);
  415. }
  416. hotUpdate (newOptions) {
  417. this._modules.update(newOptions);
  418. resetStore(this, true);
  419. }
  420. _withCommit (fn) {
  421. const committing = this._committing;
  422. this._committing = true;
  423. fn();
  424. this._committing = committing;
  425. }
  426. }
  427. function genericSubscribe (fn, subs) {
  428. if (subs.indexOf(fn) < 0) {
  429. subs.push(fn);
  430. }
  431. return () => {
  432. const i = subs.indexOf(fn);
  433. if (i > -1) {
  434. subs.splice(i, 1);
  435. }
  436. }
  437. }
  438. function resetStore (store, hot) {
  439. store._actions = Object.create(null);
  440. store._mutations = Object.create(null);
  441. store._wrappedGetters = Object.create(null);
  442. store._modulesNamespaceMap = Object.create(null);
  443. const state = store.state;
  444. // init all modules
  445. installModule(store, state, [], store._modules.root, true);
  446. // reset vm
  447. resetStoreVM(store, state, hot);
  448. }
  449. function resetStoreVM (store, state, hot) {
  450. const oldVm = store._vm;
  451. // bind store public getters
  452. store.getters = {};
  453. // reset local getters cache
  454. store._makeLocalGettersCache = Object.create(null);
  455. const wrappedGetters = store._wrappedGetters;
  456. const computed = {};
  457. forEachValue(wrappedGetters, (fn, key) => {
  458. // use computed to leverage its lazy-caching mechanism
  459. // direct inline function use will lead to closure preserving oldVm.
  460. // using partial to return function with only arguments preserved in closure environment.
  461. computed[key] = partial(fn, store);
  462. Object.defineProperty(store.getters, key, {
  463. get: () => store._vm[key],
  464. enumerable: true // for local getters
  465. });
  466. });
  467. // use a Vue instance to store the state tree
  468. // suppress warnings just in case the user has added
  469. // some funky global mixins
  470. const silent = Vue.config.silent;
  471. Vue.config.silent = true;
  472. store._vm = new Vue({
  473. data: {
  474. $$state: state
  475. },
  476. computed
  477. });
  478. Vue.config.silent = silent;
  479. // enable strict mode for new vm
  480. if (store.strict) {
  481. enableStrictMode(store);
  482. }
  483. if (oldVm) {
  484. if (hot) {
  485. // dispatch changes in all subscribed watchers
  486. // to force getter re-evaluation for hot reloading.
  487. store._withCommit(() => {
  488. oldVm._data.$$state = null;
  489. });
  490. }
  491. Vue.nextTick(() => oldVm.$destroy());
  492. }
  493. }
  494. function installModule (store, rootState, path, module, hot) {
  495. const isRoot = !path.length;
  496. const namespace = store._modules.getNamespace(path);
  497. // register in namespace map
  498. if (module.namespaced) {
  499. if (store._modulesNamespaceMap[namespace] && "development" !== 'production') {
  500. console.error(`[vuex] duplicate namespace ${namespace} for the namespaced module ${path.join('/')}`);
  501. }
  502. store._modulesNamespaceMap[namespace] = module;
  503. }
  504. // set state
  505. if (!isRoot && !hot) {
  506. const parentState = getNestedState(rootState, path.slice(0, -1));
  507. const moduleName = path[path.length - 1];
  508. store._withCommit(() => {
  509. {
  510. if (moduleName in parentState) {
  511. console.warn(
  512. `[vuex] state field "${moduleName}" was overridden by a module with the same name at "${path.join('.')}"`
  513. );
  514. }
  515. }
  516. Vue.set(parentState, moduleName, module.state);
  517. });
  518. }
  519. const local = module.context = makeLocalContext(store, namespace, path);
  520. module.forEachMutation((mutation, key) => {
  521. const namespacedType = namespace + key;
  522. registerMutation(store, namespacedType, mutation, local);
  523. });
  524. module.forEachAction((action, key) => {
  525. const type = action.root ? key : namespace + key;
  526. const handler = action.handler || action;
  527. registerAction(store, type, handler, local);
  528. });
  529. module.forEachGetter((getter, key) => {
  530. const namespacedType = namespace + key;
  531. registerGetter(store, namespacedType, getter, local);
  532. });
  533. module.forEachChild((child, key) => {
  534. installModule(store, rootState, path.concat(key), child, hot);
  535. });
  536. }
  537. /**
  538. * make localized dispatch, commit, getters and state
  539. * if there is no namespace, just use root ones
  540. */
  541. function makeLocalContext (store, namespace, path) {
  542. const noNamespace = namespace === '';
  543. const local = {
  544. dispatch: noNamespace ? store.dispatch : (_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._actions[type]) {
  551. console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`);
  552. return
  553. }
  554. }
  555. return store.dispatch(type, payload)
  556. },
  557. commit: noNamespace ? store.commit : (_type, _payload, _options) => {
  558. const args = unifyObjectStyle(_type, _payload, _options);
  559. const { payload, options } = args;
  560. let { type } = args;
  561. if (!options || !options.root) {
  562. type = namespace + type;
  563. if (!store._mutations[type]) {
  564. console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`);
  565. return
  566. }
  567. }
  568. store.commit(type, payload, options);
  569. }
  570. };
  571. // getters and state object must be gotten lazily
  572. // because they will be changed by vm update
  573. Object.defineProperties(local, {
  574. getters: {
  575. get: noNamespace
  576. ? () => store.getters
  577. : () => makeLocalGetters(store, namespace)
  578. },
  579. state: {
  580. get: () => getNestedState(store.state, path)
  581. }
  582. });
  583. return local
  584. }
  585. function makeLocalGetters (store, namespace) {
  586. if (!store._makeLocalGettersCache[namespace]) {
  587. const gettersProxy = {};
  588. const splitPos = namespace.length;
  589. Object.keys(store.getters).forEach(type => {
  590. // skip if the target getter is not match this namespace
  591. if (type.slice(0, splitPos) !== namespace) return
  592. // extract local getter type
  593. const localType = type.slice(splitPos);
  594. // Add a port to the getters proxy.
  595. // Define as getter property because
  596. // we do not want to evaluate the getters in this time.
  597. Object.defineProperty(gettersProxy, localType, {
  598. get: () => store.getters[type],
  599. enumerable: true
  600. });
  601. });
  602. store._makeLocalGettersCache[namespace] = gettersProxy;
  603. }
  604. return store._makeLocalGettersCache[namespace]
  605. }
  606. function registerMutation (store, type, handler, local) {
  607. const entry = store._mutations[type] || (store._mutations[type] = []);
  608. entry.push(function wrappedMutationHandler (payload) {
  609. handler.call(store, local.state, payload);
  610. });
  611. }
  612. function registerAction (store, type, handler, local) {
  613. const entry = store._actions[type] || (store._actions[type] = []);
  614. entry.push(function wrappedActionHandler (payload) {
  615. let res = handler.call(store, {
  616. dispatch: local.dispatch,
  617. commit: local.commit,
  618. getters: local.getters,
  619. state: local.state,
  620. rootGetters: store.getters,
  621. rootState: store.state
  622. }, payload);
  623. if (!isPromise(res)) {
  624. res = Promise.resolve(res);
  625. }
  626. if (store._devtoolHook) {
  627. return res.catch(err => {
  628. store._devtoolHook.emit('vuex:error', err);
  629. throw err
  630. })
  631. } else {
  632. return res
  633. }
  634. });
  635. }
  636. function registerGetter (store, type, rawGetter, local) {
  637. if (store._wrappedGetters[type]) {
  638. {
  639. console.error(`[vuex] duplicate getter key: ${type}`);
  640. }
  641. return
  642. }
  643. store._wrappedGetters[type] = function wrappedGetter (store) {
  644. return rawGetter(
  645. local.state, // local state
  646. local.getters, // local getters
  647. store.state, // root state
  648. store.getters // root getters
  649. )
  650. };
  651. }
  652. function enableStrictMode (store) {
  653. store._vm.$watch(function () { return this._data.$$state }, () => {
  654. {
  655. assert(store._committing, `do not mutate vuex store state outside mutation handlers.`);
  656. }
  657. }, { deep: true, sync: true });
  658. }
  659. function getNestedState (state, path) {
  660. return path.length
  661. ? path.reduce((state, key) => state[key], state)
  662. : state
  663. }
  664. function unifyObjectStyle (type, payload, options) {
  665. if (isObject(type) && type.type) {
  666. options = payload;
  667. payload = type;
  668. type = type.type;
  669. }
  670. {
  671. assert(typeof type === 'string', `expects string as the type, but found ${typeof type}.`);
  672. }
  673. return { type, payload, options }
  674. }
  675. function install (_Vue) {
  676. if (Vue && _Vue === Vue) {
  677. {
  678. console.error(
  679. '[vuex] already installed. Vue.use(Vuex) should be called only once.'
  680. );
  681. }
  682. return
  683. }
  684. Vue = _Vue;
  685. applyMixin(Vue);
  686. }
  687. /**
  688. * Reduce the code which written in Vue.js for getting the state.
  689. * @param {String} [namespace] - Module's namespace
  690. * @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.
  691. * @param {Object}
  692. */
  693. const mapState = normalizeNamespace((namespace, states) => {
  694. const res = {};
  695. if (!isValidMap(states)) {
  696. console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
  697. }
  698. normalizeMap(states).forEach(({ key, val }) => {
  699. res[key] = function mappedState () {
  700. let state = this.$store.state;
  701. let getters = this.$store.getters;
  702. if (namespace) {
  703. const module = getModuleByNamespace(this.$store, 'mapState', namespace);
  704. if (!module) {
  705. return
  706. }
  707. state = module.context.state;
  708. getters = module.context.getters;
  709. }
  710. return typeof val === 'function'
  711. ? val.call(this, state, getters)
  712. : state[val]
  713. };
  714. // mark vuex getter for devtools
  715. res[key].vuex = true;
  716. });
  717. return res
  718. });
  719. /**
  720. * Reduce the code which written in Vue.js for committing the mutation
  721. * @param {String} [namespace] - Module's namespace
  722. * @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.
  723. * @return {Object}
  724. */
  725. const mapMutations = normalizeNamespace((namespace, mutations) => {
  726. const res = {};
  727. if (!isValidMap(mutations)) {
  728. console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
  729. }
  730. normalizeMap(mutations).forEach(({ key, val }) => {
  731. res[key] = function mappedMutation (...args) {
  732. // Get the commit method from store
  733. let commit = this.$store.commit;
  734. if (namespace) {
  735. const module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
  736. if (!module) {
  737. return
  738. }
  739. commit = module.context.commit;
  740. }
  741. return typeof val === 'function'
  742. ? val.apply(this, [commit].concat(args))
  743. : commit.apply(this.$store, [val].concat(args))
  744. };
  745. });
  746. return res
  747. });
  748. /**
  749. * Reduce the code which written in Vue.js for getting the getters
  750. * @param {String} [namespace] - Module's namespace
  751. * @param {Object|Array} getters
  752. * @return {Object}
  753. */
  754. const mapGetters = normalizeNamespace((namespace, getters) => {
  755. const res = {};
  756. if (!isValidMap(getters)) {
  757. console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
  758. }
  759. normalizeMap(getters).forEach(({ key, val }) => {
  760. // The namespace has been mutated by normalizeNamespace
  761. val = namespace + val;
  762. res[key] = function mappedGetter () {
  763. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  764. return
  765. }
  766. if (!(val in this.$store.getters)) {
  767. console.error(`[vuex] unknown getter: ${val}`);
  768. return
  769. }
  770. return this.$store.getters[val]
  771. };
  772. // mark vuex getter for devtools
  773. res[key].vuex = true;
  774. });
  775. return res
  776. });
  777. /**
  778. * Reduce the code which written in Vue.js for dispatch the action
  779. * @param {String} [namespace] - Module's namespace
  780. * @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.
  781. * @return {Object}
  782. */
  783. const mapActions = normalizeNamespace((namespace, actions) => {
  784. const res = {};
  785. if (!isValidMap(actions)) {
  786. console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
  787. }
  788. normalizeMap(actions).forEach(({ key, val }) => {
  789. res[key] = function mappedAction (...args) {
  790. // get dispatch function from store
  791. let dispatch = this.$store.dispatch;
  792. if (namespace) {
  793. const module = getModuleByNamespace(this.$store, 'mapActions', namespace);
  794. if (!module) {
  795. return
  796. }
  797. dispatch = module.context.dispatch;
  798. }
  799. return typeof val === 'function'
  800. ? val.apply(this, [dispatch].concat(args))
  801. : dispatch.apply(this.$store, [val].concat(args))
  802. };
  803. });
  804. return res
  805. });
  806. /**
  807. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  808. * @param {String} namespace
  809. * @return {Object}
  810. */
  811. const createNamespacedHelpers = (namespace) => ({
  812. mapState: mapState.bind(null, namespace),
  813. mapGetters: mapGetters.bind(null, namespace),
  814. mapMutations: mapMutations.bind(null, namespace),
  815. mapActions: mapActions.bind(null, namespace)
  816. });
  817. /**
  818. * Normalize the map
  819. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  820. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  821. * @param {Array|Object} map
  822. * @return {Object}
  823. */
  824. function normalizeMap (map) {
  825. if (!isValidMap(map)) {
  826. return []
  827. }
  828. return Array.isArray(map)
  829. ? map.map(key => ({ key, val: key }))
  830. : Object.keys(map).map(key => ({ key, val: map[key] }))
  831. }
  832. /**
  833. * Validate whether given map is valid or not
  834. * @param {*} map
  835. * @return {Boolean}
  836. */
  837. function isValidMap (map) {
  838. return Array.isArray(map) || isObject(map)
  839. }
  840. /**
  841. * 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.
  842. * @param {Function} fn
  843. * @return {Function}
  844. */
  845. function normalizeNamespace (fn) {
  846. return (namespace, map) => {
  847. if (typeof namespace !== 'string') {
  848. map = namespace;
  849. namespace = '';
  850. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  851. namespace += '/';
  852. }
  853. return fn(namespace, map)
  854. }
  855. }
  856. /**
  857. * Search a special module from store by namespace. if module not exist, print error message.
  858. * @param {Object} store
  859. * @param {String} helper
  860. * @param {String} namespace
  861. * @return {Object}
  862. */
  863. function getModuleByNamespace (store, helper, namespace) {
  864. const module = store._modulesNamespaceMap[namespace];
  865. if (!module) {
  866. console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`);
  867. }
  868. return module
  869. }
  870. var index_esm = {
  871. Store,
  872. install,
  873. version: '3.1.2',
  874. mapState,
  875. mapMutations,
  876. mapGetters,
  877. mapActions,
  878. createNamespacedHelpers
  879. };
  880. export default index_esm;
  881. export { Store, install, mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers };