vuex.common.js 36 KB

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