vuex.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*!
  2. * Vuex v0.5.0
  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. Object.keys(targetState).forEach(function (key) {
  93. currentState[key] = targetState[key];
  94. });
  95. });
  96. },
  97. onMutation: function onMutation(mutation, state) {
  98. if (!hook) return;
  99. hook.emit('vuex:mutation', mutation, state);
  100. }
  101. };
  102. // export install function
  103. function override (Vue) {
  104. var _init = Vue.prototype._init;
  105. Vue.prototype._init = function (options) {
  106. var _this = this;
  107. options = options || {};
  108. var componentOptions = this.constructor.options;
  109. // store injection
  110. var store = options.store || componentOptions.store;
  111. if (store) {
  112. this.$store = store;
  113. } else if (options.parent && options.parent.$store) {
  114. this.$store = options.parent.$store;
  115. }
  116. // vuex option handling
  117. var vuex = options.vuex || componentOptions.vuex;
  118. if (vuex) {
  119. (function () {
  120. if (!_this.$store) {
  121. console.warn('[vuex] store not injected. make sure to ' + 'provide the store option in your root component.');
  122. }
  123. var state = vuex.state;
  124. var actions = vuex.actions;
  125. // state
  126. if (state) {
  127. options.computed = options.computed || {};
  128. Object.keys(state).forEach(function (key) {
  129. options.computed[key] = function vuexBoundGetter() {
  130. return state[key].call(this, this.$store.state);
  131. };
  132. });
  133. }
  134. // actions
  135. if (actions) {
  136. options.methods = options.methods || {};
  137. Object.keys(actions).forEach(function (key) {
  138. options.methods[key] = function vuexBoundAction() {
  139. var _actions$key;
  140. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  141. args[_key] = arguments[_key];
  142. }
  143. return (_actions$key = actions[key]).call.apply(_actions$key, [this, this.$store].concat(args));
  144. };
  145. });
  146. }
  147. })();
  148. }
  149. _init.call(this, options);
  150. };
  151. }
  152. var Vue = undefined;
  153. var Store = function () {
  154. /**
  155. * @param {Object} options
  156. * - {Object} state
  157. * - {Object} actions
  158. * - {Object} mutations
  159. * - {Array} middlewares
  160. * - {Boolean} strict
  161. */
  162. function Store() {
  163. var _this = this;
  164. var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  165. var _ref$state = _ref.state;
  166. var state = _ref$state === undefined ? {} : _ref$state;
  167. var _ref$mutations = _ref.mutations;
  168. var mutations = _ref$mutations === undefined ? {} : _ref$mutations;
  169. var _ref$modules = _ref.modules;
  170. var modules = _ref$modules === undefined ? {} : _ref$modules;
  171. var _ref$middlewares = _ref.middlewares;
  172. var middlewares = _ref$middlewares === undefined ? [] : _ref$middlewares;
  173. var _ref$strict = _ref.strict;
  174. var strict = _ref$strict === undefined ? false : _ref$strict;
  175. babelHelpers.classCallCheck(this, Store);
  176. this._dispatching = false;
  177. this._rootMutations = this._mutations = mutations;
  178. this._modules = modules;
  179. // bind dispatch to self
  180. var dispatch = this.dispatch;
  181. this.dispatch = function () {
  182. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  183. args[_key] = arguments[_key];
  184. }
  185. dispatch.apply(_this, args);
  186. };
  187. // use a Vue instance to store the state tree
  188. // suppress warnings just in case the user has added
  189. // some funky global mixins
  190. var silent = Vue.config.silent;
  191. Vue.config.silent = true;
  192. this._vm = new Vue({
  193. data: state
  194. });
  195. Vue.config.silent = silent;
  196. this._setupModuleState(state, modules);
  197. this._setupModuleMutations(modules);
  198. this._setupMiddlewares(middlewares, state);
  199. // add extra warnings in strict mode
  200. if (strict) {
  201. this._setupMutationCheck();
  202. }
  203. }
  204. /**
  205. * Getter for the entire state tree.
  206. * Read only.
  207. *
  208. * @return {Object}
  209. */
  210. babelHelpers.createClass(Store, [{
  211. key: 'dispatch',
  212. /**
  213. * Dispatch an action.
  214. *
  215. * @param {String} type
  216. */
  217. value: function dispatch(type) {
  218. var _this2 = this;
  219. for (var _len2 = arguments.length, payload = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  220. payload[_key2 - 1] = arguments[_key2];
  221. }
  222. var mutation = this._mutations[type];
  223. var prevSnapshot = this._prevSnapshot;
  224. var state = this.state;
  225. var snapshot = undefined,
  226. clonedPayload = undefined;
  227. if (mutation) {
  228. this._dispatching = true;
  229. // apply the mutation
  230. if (Array.isArray(mutation)) {
  231. mutation.forEach(function (m) {
  232. return m.apply(undefined, [state].concat(payload));
  233. });
  234. } else {
  235. mutation.apply(undefined, [state].concat(payload));
  236. }
  237. this._dispatching = false;
  238. // invoke middlewares
  239. if (this._needSnapshots) {
  240. snapshot = this._prevSnapshot = deepClone(state);
  241. clonedPayload = deepClone(payload);
  242. }
  243. this._middlewares.forEach(function (m) {
  244. if (m.onMutation) {
  245. if (m.snapshot) {
  246. m.onMutation({ type: type, payload: clonedPayload }, snapshot, prevSnapshot, _this2);
  247. } else {
  248. m.onMutation({ type: type, payload: payload }, state, _this2);
  249. }
  250. }
  251. });
  252. } else {
  253. console.warn('[vuex] Unknown mutation: ' + type);
  254. }
  255. }
  256. /**
  257. * Watch state changes on the store.
  258. * Same API as Vue's $watch, except when watching a function,
  259. * the function gets the state as the first argument.
  260. *
  261. * @param {String|Function} expOrFn
  262. * @param {Function} cb
  263. * @param {Object} [options]
  264. */
  265. }, {
  266. key: 'watch',
  267. value: function watch(expOrFn, cb, options) {
  268. var _this3 = this;
  269. return this._vm.$watch(function () {
  270. return typeof expOrFn === 'function' ? expOrFn(_this3.state) : _this3._vm.$get(expOrFn);
  271. }, cb, options);
  272. }
  273. /**
  274. * Hot update actions and mutations.
  275. *
  276. * @param {Object} options
  277. * - {Object} [mutations]
  278. * - {Object} [modules]
  279. */
  280. }, {
  281. key: 'hotUpdate',
  282. value: function hotUpdate() {
  283. var _ref2 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  284. var mutations = _ref2.mutations;
  285. var modules = _ref2.modules;
  286. this._rootMutations = this._mutations = mutations || this._rootMutations;
  287. this._setupModuleMutations(modules || this._modules);
  288. }
  289. /**
  290. * Attach sub state tree of each module to the root tree.
  291. *
  292. * @param {Object} state
  293. * @param {Object} modules
  294. */
  295. }, {
  296. key: '_setupModuleState',
  297. value: function _setupModuleState(state, modules) {
  298. var setPath = Vue.parsers.path.setPath;
  299. Object.keys(modules).forEach(function (key) {
  300. setPath(state, key, modules[key].state || {});
  301. });
  302. }
  303. /**
  304. * Bind mutations for each module to its sub tree and
  305. * merge them all into one final mutations map.
  306. *
  307. * @param {Object} modules
  308. */
  309. }, {
  310. key: '_setupModuleMutations',
  311. value: function _setupModuleMutations(modules) {
  312. this._modules = modules;
  313. var getPath = Vue.parsers.path.getPath;
  314. var allMutations = [this._rootMutations];
  315. Object.keys(modules).forEach(function (key) {
  316. var module = modules[key];
  317. if (!module || !module.mutations) return;
  318. // bind mutations to sub state tree
  319. var mutations = {};
  320. Object.keys(module.mutations).forEach(function (name) {
  321. var original = module.mutations[name];
  322. mutations[name] = function (state) {
  323. for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  324. args[_key3 - 1] = arguments[_key3];
  325. }
  326. original.apply(undefined, [getPath(state, key)].concat(args));
  327. };
  328. });
  329. allMutations.push(mutations);
  330. });
  331. this._mutations = mergeObjects(allMutations);
  332. }
  333. /**
  334. * Setup mutation check: if the vuex instance's state is mutated
  335. * outside of a mutation handler, we throw en error. This effectively
  336. * enforces all mutations to the state to be trackable and hot-reloadble.
  337. * However, this comes at a run time cost since we are doing a deep
  338. * watch on the entire state tree, so it is only enalbed with the
  339. * strict option is set to true.
  340. */
  341. }, {
  342. key: '_setupMutationCheck',
  343. value: function _setupMutationCheck() {
  344. var _this4 = this;
  345. // a hack to get the watcher constructor from older versions of Vue
  346. // mainly because the public $watch method does not allow sync
  347. // watchers.
  348. var unwatch = this._vm.$watch('__vuex__', function (a) {
  349. return a;
  350. });
  351. var Watcher = this._vm._watchers[0].constructor;
  352. unwatch();
  353. /* eslint-disable no-new */
  354. new Watcher(this._vm, '$data', function () {
  355. if (!_this4._dispatching) {
  356. throw new Error('[vuex] Do not mutate vuex store state outside mutation handlers.');
  357. }
  358. }, { deep: true, sync: true });
  359. /* eslint-enable no-new */
  360. }
  361. /**
  362. * Setup the middlewares. The devtools middleware is always
  363. * included, since it does nothing if no devtool is detected.
  364. *
  365. * A middleware can demand the state it receives to be
  366. * "snapshots", i.e. deep clones of the actual state tree.
  367. *
  368. * @param {Array} middlewares
  369. * @param {Object} state
  370. */
  371. }, {
  372. key: '_setupMiddlewares',
  373. value: function _setupMiddlewares(middlewares, state) {
  374. var _this5 = this;
  375. this._middlewares = [devtoolMiddleware].concat(middlewares);
  376. this._needSnapshots = middlewares.some(function (m) {
  377. return m.snapshot;
  378. });
  379. if (this._needSnapshots) {
  380. console.log('[vuex] One or more of your middlewares are taking state snapshots ' + 'for each mutation. Make sure to use them only during development.');
  381. }
  382. var initialSnapshot = this._prevSnapshot = this._needSnapshots ? deepClone(state) : null;
  383. // call init hooks
  384. this._middlewares.forEach(function (m) {
  385. if (m.onInit) {
  386. m.onInit(m.snapshot ? initialSnapshot : state, _this5);
  387. }
  388. });
  389. }
  390. }, {
  391. key: 'state',
  392. get: function get() {
  393. return this._vm._data;
  394. },
  395. set: function set(v) {
  396. throw new Error('[vuex] Vuex root state is read only.');
  397. }
  398. }]);
  399. return Store;
  400. }();
  401. function install(_Vue) {
  402. Vue = _Vue;
  403. override(Vue);
  404. }
  405. var index = {
  406. Store: Store,
  407. install: install
  408. };
  409. return index;
  410. }));