vuex.common.js 36 KB

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