vuex.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /*!
  2. * Vuex v0.5.1
  3. * (c) 2016 Evan You
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.Vuex = factory());
  10. }(this, function () { 'use strict';
  11. var babelHelpers = {};
  12. babelHelpers.typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  13. return typeof obj;
  14. } : function (obj) {
  15. return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
  16. };
  17. babelHelpers.classCallCheck = function (instance, Constructor) {
  18. if (!(instance instanceof Constructor)) {
  19. throw new TypeError("Cannot call a class as a function");
  20. }
  21. };
  22. babelHelpers.createClass = function () {
  23. function defineProperties(target, props) {
  24. for (var i = 0; i < props.length; i++) {
  25. var descriptor = props[i];
  26. descriptor.enumerable = descriptor.enumerable || false;
  27. descriptor.configurable = true;
  28. if ("value" in descriptor) descriptor.writable = true;
  29. Object.defineProperty(target, descriptor.key, descriptor);
  30. }
  31. }
  32. return function (Constructor, protoProps, staticProps) {
  33. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  34. if (staticProps) defineProperties(Constructor, staticProps);
  35. return Constructor;
  36. };
  37. }();
  38. babelHelpers;
  39. /**
  40. * Merge an array of objects into one.
  41. *
  42. * @param {Array<Object>} arr
  43. * @return {Object}
  44. */
  45. function mergeObjects(arr) {
  46. return arr.reduce(function (prev, obj) {
  47. Object.keys(obj).forEach(function (key) {
  48. var existing = prev[key];
  49. if (existing) {
  50. // allow multiple mutation objects to contain duplicate
  51. // handlers for the same mutation type
  52. if (Array.isArray(existing)) {
  53. existing.push(obj[key]);
  54. } else {
  55. prev[key] = [prev[key], obj[key]];
  56. }
  57. } else {
  58. prev[key] = obj[key];
  59. }
  60. });
  61. return prev;
  62. }, {});
  63. }
  64. /**
  65. * Deep clone an object. Faster than JSON.parse(JSON.stringify()).
  66. *
  67. * @param {*} obj
  68. * @return {*}
  69. */
  70. function deepClone(obj) {
  71. if (Array.isArray(obj)) {
  72. return obj.map(deepClone);
  73. } else if (obj && (typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj)) === 'object') {
  74. var cloned = {};
  75. var keys = Object.keys(obj);
  76. for (var i = 0, l = keys.length; i < l; i++) {
  77. var key = keys[i];
  78. cloned[key] = deepClone(obj[key]);
  79. }
  80. return cloned;
  81. } else {
  82. return obj;
  83. }
  84. }
  85. var hook = typeof window !== 'undefined' && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
  86. var devtoolMiddleware = {
  87. onInit: function onInit(state, store) {
  88. if (!hook) return;
  89. hook.emit('vuex:init', store);
  90. hook.on('vuex:travel-to-state', function (targetState) {
  91. var currentState = store._vm._data;
  92. store._dispatching = true;
  93. Object.keys(targetState).forEach(function (key) {
  94. currentState[key] = targetState[key];
  95. });
  96. store._dispatching = false;
  97. });
  98. },
  99. onMutation: function onMutation(mutation, state) {
  100. if (!hook) return;
  101. hook.emit('vuex:mutation', mutation, state);
  102. }
  103. };
  104. // export install function
  105. function override (Vue) {
  106. var _init = Vue.prototype._init;
  107. Vue.prototype._init = function (options) {
  108. var _this = this;
  109. options = options || {};
  110. var componentOptions = this.constructor.options;
  111. // store injection
  112. var store = options.store || componentOptions.store;
  113. if (store) {
  114. this.$store = store;
  115. } else if (options.parent && options.parent.$store) {
  116. this.$store = options.parent.$store;
  117. }
  118. // vuex option handling
  119. var vuex = options.vuex || componentOptions.vuex;
  120. if (vuex) {
  121. (function () {
  122. if (!_this.$store) {
  123. console.warn('[vuex] store not injected. make sure to ' + 'provide the store option in your root component.');
  124. }
  125. var state = vuex.state;
  126. var actions = vuex.actions;
  127. // state
  128. if (state) {
  129. options.computed = options.computed || {};
  130. Object.keys(state).forEach(function (key) {
  131. options.computed[key] = function vuexBoundGetter() {
  132. return state[key].call(this, this.$store.state);
  133. };
  134. });
  135. }
  136. // actions
  137. if (actions) {
  138. options.methods = options.methods || {};
  139. Object.keys(actions).forEach(function (key) {
  140. options.methods[key] = function vuexBoundAction() {
  141. var _actions$key;
  142. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  143. args[_key] = arguments[_key];
  144. }
  145. return (_actions$key = actions[key]).call.apply(_actions$key, [this, this.$store].concat(args));
  146. };
  147. });
  148. }
  149. })();
  150. }
  151. _init.call(this, options);
  152. };
  153. }
  154. var Vue = undefined;
  155. var Store = function () {
  156. /**
  157. * @param {Object} options
  158. * - {Object} state
  159. * - {Object} actions
  160. * - {Object} mutations
  161. * - {Array} middlewares
  162. * - {Boolean} strict
  163. */
  164. function Store() {
  165. var _this = this;
  166. var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  167. var _ref$state = _ref.state;
  168. var state = _ref$state === undefined ? {} : _ref$state;
  169. var _ref$mutations = _ref.mutations;
  170. var mutations = _ref$mutations === undefined ? {} : _ref$mutations;
  171. var _ref$modules = _ref.modules;
  172. var modules = _ref$modules === undefined ? {} : _ref$modules;
  173. var _ref$middlewares = _ref.middlewares;
  174. var middlewares = _ref$middlewares === undefined ? [] : _ref$middlewares;
  175. var _ref$strict = _ref.strict;
  176. var strict = _ref$strict === undefined ? false : _ref$strict;
  177. babelHelpers.classCallCheck(this, Store);
  178. this._dispatching = false;
  179. this._rootMutations = this._mutations = mutations;
  180. this._modules = modules;
  181. // bind dispatch to self
  182. var dispatch = this.dispatch;
  183. this.dispatch = function () {
  184. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  185. args[_key] = arguments[_key];
  186. }
  187. dispatch.apply(_this, args);
  188. };
  189. // use a Vue instance to store the state tree
  190. // suppress warnings just in case the user has added
  191. // some funky global mixins
  192. var silent = Vue.config.silent;
  193. Vue.config.silent = true;
  194. this._vm = new Vue({
  195. data: state
  196. });
  197. Vue.config.silent = silent;
  198. this._setupModuleState(state, modules);
  199. this._setupModuleMutations(modules);
  200. this._setupMiddlewares(middlewares, state);
  201. // add extra warnings in strict mode
  202. if (strict) {
  203. this._setupMutationCheck();
  204. }
  205. }
  206. /**
  207. * Getter for the entire state tree.
  208. * Read only.
  209. *
  210. * @return {Object}
  211. */
  212. babelHelpers.createClass(Store, [{
  213. key: 'dispatch',
  214. /**
  215. * Dispatch an action.
  216. *
  217. * @param {String} type
  218. */
  219. value: function dispatch(type) {
  220. var _this2 = this;
  221. for (var _len2 = arguments.length, payload = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  222. payload[_key2 - 1] = arguments[_key2];
  223. }
  224. var mutation = this._mutations[type];
  225. var prevSnapshot = this._prevSnapshot;
  226. var state = this.state;
  227. var snapshot = undefined,
  228. clonedPayload = undefined;
  229. if (mutation) {
  230. this._dispatching = true;
  231. // apply the mutation
  232. if (Array.isArray(mutation)) {
  233. mutation.forEach(function (m) {
  234. return m.apply(undefined, [state].concat(payload));
  235. });
  236. } else {
  237. mutation.apply(undefined, [state].concat(payload));
  238. }
  239. this._dispatching = false;
  240. // invoke middlewares
  241. if (this._needSnapshots) {
  242. snapshot = this._prevSnapshot = deepClone(state);
  243. clonedPayload = deepClone(payload);
  244. }
  245. this._middlewares.forEach(function (m) {
  246. if (m.onMutation) {
  247. if (m.snapshot) {
  248. m.onMutation({ type: type, payload: clonedPayload }, snapshot, prevSnapshot, _this2);
  249. } else {
  250. m.onMutation({ type: type, payload: payload }, state, _this2);
  251. }
  252. }
  253. });
  254. } else {
  255. console.warn('[vuex] Unknown mutation: ' + type);
  256. }
  257. }
  258. /**
  259. * Watch state changes on the store.
  260. * Same API as Vue's $watch, except when watching a function,
  261. * the function gets the state as the first argument.
  262. *
  263. * @param {String|Function} expOrFn
  264. * @param {Function} cb
  265. * @param {Object} [options]
  266. */
  267. }, {
  268. key: 'watch',
  269. value: function watch(expOrFn, cb, options) {
  270. var _this3 = this;
  271. return this._vm.$watch(function () {
  272. return typeof expOrFn === 'function' ? expOrFn(_this3.state) : _this3._vm.$get(expOrFn);
  273. }, cb, options);
  274. }
  275. /**
  276. * Hot update actions and mutations.
  277. *
  278. * @param {Object} options
  279. * - {Object} [mutations]
  280. * - {Object} [modules]
  281. */
  282. }, {
  283. key: 'hotUpdate',
  284. value: function hotUpdate() {
  285. var _ref2 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  286. var mutations = _ref2.mutations;
  287. var modules = _ref2.modules;
  288. this._rootMutations = this._mutations = mutations || this._rootMutations;
  289. this._setupModuleMutations(modules || this._modules);
  290. }
  291. /**
  292. * Attach sub state tree of each module to the root tree.
  293. *
  294. * @param {Object} state
  295. * @param {Object} modules
  296. */
  297. }, {
  298. key: '_setupModuleState',
  299. value: function _setupModuleState(state, modules) {
  300. var setPath = Vue.parsers.path.setPath;
  301. Object.keys(modules).forEach(function (key) {
  302. setPath(state, key, modules[key].state || {});
  303. });
  304. }
  305. /**
  306. * Bind mutations for each module to its sub tree and
  307. * merge them all into one final mutations map.
  308. *
  309. * @param {Object} modules
  310. */
  311. }, {
  312. key: '_setupModuleMutations',
  313. value: function _setupModuleMutations(modules) {
  314. this._modules = modules;
  315. var getPath = Vue.parsers.path.getPath;
  316. var allMutations = [this._rootMutations];
  317. Object.keys(modules).forEach(function (key) {
  318. var module = modules[key];
  319. if (!module || !module.mutations) return;
  320. // bind mutations to sub state tree
  321. var mutations = {};
  322. Object.keys(module.mutations).forEach(function (name) {
  323. var original = module.mutations[name];
  324. mutations[name] = function (state) {
  325. for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  326. args[_key3 - 1] = arguments[_key3];
  327. }
  328. original.apply(undefined, [getPath(state, key)].concat(args));
  329. };
  330. });
  331. allMutations.push(mutations);
  332. });
  333. this._mutations = mergeObjects(allMutations);
  334. }
  335. /**
  336. * Setup mutation check: if the vuex instance's state is mutated
  337. * outside of a mutation handler, we throw en error. This effectively
  338. * enforces all mutations to the state to be trackable and hot-reloadble.
  339. * However, this comes at a run time cost since we are doing a deep
  340. * watch on the entire state tree, so it is only enalbed with the
  341. * strict option is set to true.
  342. */
  343. }, {
  344. key: '_setupMutationCheck',
  345. value: function _setupMutationCheck() {
  346. var _this4 = this;
  347. // a hack to get the watcher constructor from older versions of Vue
  348. // mainly because the public $watch method does not allow sync
  349. // watchers.
  350. var unwatch = this._vm.$watch('__vuex__', function (a) {
  351. return a;
  352. });
  353. var Watcher = this._vm._watchers[0].constructor;
  354. unwatch();
  355. /* eslint-disable no-new */
  356. new Watcher(this._vm, '$data', function () {
  357. if (!_this4._dispatching) {
  358. throw new Error('[vuex] Do not mutate vuex store state outside mutation handlers.');
  359. }
  360. }, { deep: true, sync: true });
  361. /* eslint-enable no-new */
  362. }
  363. /**
  364. * Setup the middlewares. The devtools middleware is always
  365. * included, since it does nothing if no devtool is detected.
  366. *
  367. * A middleware can demand the state it receives to be
  368. * "snapshots", i.e. deep clones of the actual state tree.
  369. *
  370. * @param {Array} middlewares
  371. * @param {Object} state
  372. */
  373. }, {
  374. key: '_setupMiddlewares',
  375. value: function _setupMiddlewares(middlewares, state) {
  376. var _this5 = this;
  377. this._middlewares = [devtoolMiddleware].concat(middlewares);
  378. this._needSnapshots = middlewares.some(function (m) {
  379. return m.snapshot;
  380. });
  381. if (this._needSnapshots) {
  382. console.log('[vuex] One or more of your middlewares are taking state snapshots ' + 'for each mutation. Make sure to use them only during development.');
  383. }
  384. var initialSnapshot = this._prevSnapshot = this._needSnapshots ? deepClone(state) : null;
  385. // call init hooks
  386. this._middlewares.forEach(function (m) {
  387. if (m.onInit) {
  388. m.onInit(m.snapshot ? initialSnapshot : state, _this5);
  389. }
  390. });
  391. }
  392. }, {
  393. key: 'state',
  394. get: function get() {
  395. return this._vm._data;
  396. },
  397. set: function set(v) {
  398. throw new Error('[vuex] Vuex root state is read only.');
  399. }
  400. }]);
  401. return Store;
  402. }();
  403. function install(_Vue) {
  404. Vue = _Vue;
  405. override(Vue);
  406. }
  407. function createLogger() {
  408. console.warn('[vuex] Vuex.createLogger has been deprecated.' + 'Use `import createLogger from \'vuex/logger\' instead.');
  409. }
  410. var index = {
  411. Store: Store,
  412. install: install,
  413. createLogger: createLogger
  414. };
  415. return index;
  416. }));