vuex.esm.browser.js 32 KB

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