vuex.esm.browser.js 28 KB

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