1
0

vuex.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. /*!
  2. * Vuex v1.0.0-rc.2
  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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  12. return typeof obj;
  13. } : function (obj) {
  14. return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
  15. };
  16. var classCallCheck = function (instance, Constructor) {
  17. if (!(instance instanceof Constructor)) {
  18. throw new TypeError("Cannot call a class as a function");
  19. }
  20. };
  21. var createClass = function () {
  22. function defineProperties(target, props) {
  23. for (var i = 0; i < props.length; i++) {
  24. var descriptor = props[i];
  25. descriptor.enumerable = descriptor.enumerable || false;
  26. descriptor.configurable = true;
  27. if ("value" in descriptor) descriptor.writable = true;
  28. Object.defineProperty(target, descriptor.key, descriptor);
  29. }
  30. }
  31. return function (Constructor, protoProps, staticProps) {
  32. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  33. if (staticProps) defineProperties(Constructor, staticProps);
  34. return Constructor;
  35. };
  36. }();
  37. var toConsumableArray = function (arr) {
  38. if (Array.isArray(arr)) {
  39. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  40. return arr2;
  41. } else {
  42. return Array.from(arr);
  43. }
  44. };
  45. /**
  46. * Merge an array of objects into one.
  47. *
  48. * @param {Array<Object>} arr
  49. * @return {Object}
  50. */
  51. function mergeObjects(arr) {
  52. return arr.reduce(function (prev, obj) {
  53. Object.keys(obj).forEach(function (key) {
  54. var existing = prev[key];
  55. if (existing) {
  56. // allow multiple mutation objects to contain duplicate
  57. // handlers for the same mutation type
  58. if (Array.isArray(existing)) {
  59. prev[key] = existing.concat(obj[key]);
  60. } else {
  61. prev[key] = [existing].concat(obj[key]);
  62. }
  63. } else {
  64. prev[key] = obj[key];
  65. }
  66. });
  67. return prev;
  68. }, {});
  69. }
  70. /**
  71. * Check whether the given value is Object or not
  72. *
  73. * @param {*} obj
  74. * @return {Boolean}
  75. */
  76. function isObject(obj) {
  77. return obj !== null && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object';
  78. }
  79. /**
  80. * Get state sub tree by given keys.
  81. *
  82. * @param {Object} state
  83. * @param {Array<String>} nestedKeys
  84. * @return {Object}
  85. */
  86. function getNestedState(state, nestedKeys) {
  87. return nestedKeys.reduce(function (state, key) {
  88. return state[key];
  89. }, state);
  90. }
  91. /**
  92. * Hacks to get access to Vue internals.
  93. * Maybe we should expose these...
  94. */
  95. var Watcher = void 0;
  96. function getWatcher(vm) {
  97. if (!Watcher) {
  98. var noop = function noop() {};
  99. var unwatch = vm.$watch(noop, noop);
  100. Watcher = vm._watchers[0].constructor;
  101. unwatch();
  102. }
  103. return Watcher;
  104. }
  105. var Dep = void 0;
  106. function getDep(vm) {
  107. if (!Dep) {
  108. Dep = vm._data.__ob__.dep.constructor;
  109. }
  110. return Dep;
  111. }
  112. var hook = typeof window !== 'undefined' && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
  113. function devtoolPlugin(store) {
  114. if (!hook) return;
  115. hook.emit('vuex:init', store);
  116. hook.on('vuex:travel-to-state', function (targetState) {
  117. store.replaceState(targetState);
  118. });
  119. store.subscribe(function (mutation, state) {
  120. hook.emit('vuex:mutation', mutation, state);
  121. });
  122. }
  123. function override (Vue) {
  124. var version = Number(Vue.version.split('.')[0]);
  125. if (version >= 2) {
  126. var usesInit = Vue.config._lifecycleHooks.indexOf('init') > -1;
  127. Vue.mixin(usesInit ? { init: vuexInit } : { beforeCreate: vuexInit });
  128. } else {
  129. (function () {
  130. // override init and inject vuex init procedure
  131. // for 1.x backwards compatibility.
  132. var _init = Vue.prototype._init;
  133. Vue.prototype._init = function () {
  134. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  135. options.init = options.init ? [vuexInit].concat(options.init) : vuexInit;
  136. _init.call(this, options);
  137. };
  138. })();
  139. }
  140. /**
  141. * Vuex init hook, injected into each instances init hooks list.
  142. */
  143. function vuexInit() {
  144. var options = this.$options;
  145. var store = options.store;
  146. var vuex = options.vuex;
  147. // store injection
  148. if (store) {
  149. this.$store = store;
  150. } else if (options.parent && options.parent.$store) {
  151. this.$store = options.parent.$store;
  152. }
  153. // vuex option handling
  154. if (vuex) {
  155. if (!this.$store) {
  156. console.warn('[vuex] store not injected. make sure to ' + 'provide the store option in your root component.');
  157. }
  158. var state = vuex.state;
  159. var actions = vuex.actions;
  160. var getters = vuex.getters;
  161. // handle deprecated state option
  162. if (state && !getters) {
  163. console.warn('[vuex] vuex.state option will been deprecated in 1.0. ' + 'Use vuex.getters instead.');
  164. getters = state;
  165. }
  166. // getters
  167. if (getters) {
  168. options.computed = options.computed || {};
  169. for (var key in getters) {
  170. defineVuexGetter(this, key, getters[key]);
  171. }
  172. }
  173. // actions
  174. if (actions) {
  175. options.methods = options.methods || {};
  176. for (var _key in actions) {
  177. options.methods[_key] = makeBoundAction(this.$store, actions[_key], _key);
  178. }
  179. }
  180. }
  181. }
  182. /**
  183. * Setter for all getter properties.
  184. */
  185. function setter() {
  186. throw new Error('vuex getter properties are read-only.');
  187. }
  188. /**
  189. * Define a Vuex getter on an instance.
  190. *
  191. * @param {Vue} vm
  192. * @param {String} key
  193. * @param {Function} getter
  194. */
  195. function defineVuexGetter(vm, key, getter) {
  196. if (typeof getter !== 'function') {
  197. console.warn('[vuex] Getter bound to key \'vuex.getters.' + key + '\' is not a function.');
  198. } else {
  199. Object.defineProperty(vm, key, {
  200. enumerable: true,
  201. configurable: true,
  202. get: makeComputedGetter(vm.$store, getter),
  203. set: setter
  204. });
  205. }
  206. }
  207. /**
  208. * Make a computed getter, using the same caching mechanism of computed
  209. * properties. In addition, it is cached on the raw getter function using
  210. * the store's unique cache id. This makes the same getter shared
  211. * across all components use the same underlying watcher, and makes
  212. * the getter evaluated only once during every flush.
  213. *
  214. * @param {Store} store
  215. * @param {Function} getter
  216. */
  217. function makeComputedGetter(store, getter) {
  218. var id = store._getterCacheId;
  219. // cached
  220. if (getter[id]) {
  221. return getter[id];
  222. }
  223. var vm = store._vm;
  224. var Watcher = getWatcher(vm);
  225. var Dep = getDep(vm);
  226. var watcher = new Watcher(vm, function (vm) {
  227. return getter(vm.state);
  228. }, null, { lazy: true });
  229. var computedGetter = function computedGetter() {
  230. if (watcher.dirty) {
  231. watcher.evaluate();
  232. }
  233. if (Dep.target) {
  234. watcher.depend();
  235. }
  236. return watcher.value;
  237. };
  238. getter[id] = computedGetter;
  239. return computedGetter;
  240. }
  241. /**
  242. * Make a bound-to-store version of a raw action function.
  243. *
  244. * @param {Store} store
  245. * @param {Function} action
  246. * @param {String} key
  247. */
  248. function makeBoundAction(store, action, key) {
  249. if (typeof action !== 'function') {
  250. console.warn('[vuex] Action bound to key \'vuex.actions.' + key + '\' is not a function.');
  251. }
  252. return function vuexBoundAction() {
  253. for (var _len = arguments.length, args = Array(_len), _key2 = 0; _key2 < _len; _key2++) {
  254. args[_key2] = arguments[_key2];
  255. }
  256. return action.call.apply(action, [this, store].concat(args));
  257. };
  258. }
  259. // option merging
  260. var merge = Vue.config.optionMergeStrategies.computed;
  261. Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
  262. if (!toVal) return fromVal;
  263. if (!fromVal) return toVal;
  264. return {
  265. getters: merge(toVal.getters, fromVal.getters),
  266. state: merge(toVal.state, fromVal.state),
  267. actions: merge(toVal.actions, fromVal.actions)
  268. };
  269. };
  270. }
  271. var Vue = void 0;
  272. var uid = 0;
  273. var Store = function () {
  274. /**
  275. * @param {Object} options
  276. * - {Object} state
  277. * - {Object} actions
  278. * - {Object} mutations
  279. * - {Array} plugins
  280. * - {Boolean} strict
  281. */
  282. function Store() {
  283. var _this = this;
  284. var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  285. var _ref$state = _ref.state;
  286. var state = _ref$state === undefined ? {} : _ref$state;
  287. var _ref$mutations = _ref.mutations;
  288. var mutations = _ref$mutations === undefined ? {} : _ref$mutations;
  289. var _ref$modules = _ref.modules;
  290. var modules = _ref$modules === undefined ? {} : _ref$modules;
  291. var _ref$plugins = _ref.plugins;
  292. var plugins = _ref$plugins === undefined ? [] : _ref$plugins;
  293. var _ref$strict = _ref.strict;
  294. var strict = _ref$strict === undefined ? false : _ref$strict;
  295. classCallCheck(this, Store);
  296. this._getterCacheId = 'vuex_store_' + uid++;
  297. this._dispatching = false;
  298. this._rootMutations = this._mutations = mutations;
  299. this._modules = modules;
  300. this._subscribers = [];
  301. // bind dispatch to self
  302. var dispatch = this.dispatch;
  303. this.dispatch = function () {
  304. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  305. args[_key] = arguments[_key];
  306. }
  307. dispatch.apply(_this, args);
  308. };
  309. // use a Vue instance to store the state tree
  310. // suppress warnings just in case the user has added
  311. // some funky global mixins
  312. if (!Vue) {
  313. throw new Error('[vuex] must call Vue.use(Vuex) before creating a store instance.');
  314. }
  315. var silent = Vue.config.silent;
  316. Vue.config.silent = true;
  317. this._vm = new Vue({
  318. data: {
  319. state: state
  320. }
  321. });
  322. Vue.config.silent = silent;
  323. this._setupModuleState(state, modules);
  324. this._setupModuleMutations(modules);
  325. // add extra warnings in strict mode
  326. if (strict) {
  327. this._setupMutationCheck();
  328. }
  329. // apply plugins
  330. devtoolPlugin(this);
  331. plugins.forEach(function (plugin) {
  332. return plugin(_this);
  333. });
  334. }
  335. /**
  336. * Getter for the entire state tree.
  337. * Read only.
  338. *
  339. * @return {Object}
  340. */
  341. createClass(Store, [{
  342. key: 'replaceState',
  343. /**
  344. * Replace root state.
  345. *
  346. * @param {Object} state
  347. */
  348. value: function replaceState(state) {
  349. this._dispatching = true;
  350. this._vm.state = state;
  351. this._dispatching = false;
  352. }
  353. /**
  354. * Dispatch an action.
  355. *
  356. * @param {String} type
  357. */
  358. }, {
  359. key: 'dispatch',
  360. value: function dispatch(type) {
  361. var _this2 = this;
  362. for (var _len2 = arguments.length, payload = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  363. payload[_key2 - 1] = arguments[_key2];
  364. }
  365. var silent = false;
  366. var isObjectStyleDispatch = false;
  367. // compatibility for object actions, e.g. FSA
  368. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object' && type.type && arguments.length === 1) {
  369. isObjectStyleDispatch = true;
  370. payload = type;
  371. if (type.silent) silent = true;
  372. type = type.type;
  373. }
  374. var handler = this._mutations[type];
  375. var state = this.state;
  376. if (handler) {
  377. this._dispatching = true;
  378. // apply the mutation
  379. if (Array.isArray(handler)) {
  380. handler.forEach(function (h) {
  381. isObjectStyleDispatch ? h(state, payload) : h.apply(undefined, [state].concat(toConsumableArray(payload)));
  382. });
  383. } else {
  384. isObjectStyleDispatch ? handler(state, payload) : handler.apply(undefined, [state].concat(toConsumableArray(payload)));
  385. }
  386. this._dispatching = false;
  387. if (!silent) {
  388. (function () {
  389. var mutation = isObjectStyleDispatch ? payload : { type: type, payload: payload };
  390. _this2._subscribers.forEach(function (sub) {
  391. return sub(mutation, state);
  392. });
  393. })();
  394. }
  395. } else {
  396. console.warn('[vuex] Unknown mutation: ' + type);
  397. }
  398. }
  399. /**
  400. * Watch state changes on the store.
  401. * Same API as Vue's $watch, except when watching a function,
  402. * the function gets the state as the first argument.
  403. *
  404. * @param {Function} fn
  405. * @param {Function} cb
  406. * @param {Object} [options]
  407. */
  408. }, {
  409. key: 'watch',
  410. value: function watch(fn, cb, options) {
  411. var _this3 = this;
  412. if (typeof fn !== 'function') {
  413. console.error('Vuex store.watch only accepts function.');
  414. return;
  415. }
  416. return this._vm.$watch(function () {
  417. return fn(_this3.state);
  418. }, cb, options);
  419. }
  420. /**
  421. * Subscribe to state changes. Fires after every mutation.
  422. */
  423. }, {
  424. key: 'subscribe',
  425. value: function subscribe(fn) {
  426. var subs = this._subscribers;
  427. if (subs.indexOf(fn) < 0) {
  428. subs.push(fn);
  429. }
  430. return function () {
  431. var i = subs.indexOf(fn);
  432. if (i > -1) {
  433. subs.splice(i, 1);
  434. }
  435. };
  436. }
  437. /**
  438. * Hot update mutations & modules.
  439. *
  440. * @param {Object} options
  441. * - {Object} [mutations]
  442. * - {Object} [modules]
  443. */
  444. }, {
  445. key: 'hotUpdate',
  446. value: function hotUpdate() {
  447. var _ref2 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  448. var mutations = _ref2.mutations;
  449. var modules = _ref2.modules;
  450. this._rootMutations = this._mutations = mutations || this._rootMutations;
  451. this._setupModuleMutations(modules || this._modules);
  452. }
  453. /**
  454. * Attach sub state tree of each module to the root tree.
  455. *
  456. * @param {Object} state
  457. * @param {Object} modules
  458. */
  459. }, {
  460. key: '_setupModuleState',
  461. value: function _setupModuleState(state, modules) {
  462. var _this4 = this;
  463. if (!isObject(modules)) return;
  464. Object.keys(modules).forEach(function (key) {
  465. var module = modules[key];
  466. // set this module's state
  467. Vue.set(state, key, module.state || {});
  468. // retrieve nested modules
  469. _this4._setupModuleState(state[key], module.modules);
  470. });
  471. }
  472. /**
  473. * Bind mutations for each module to its sub tree and
  474. * merge them all into one final mutations map.
  475. *
  476. * @param {Object} updatedModules
  477. */
  478. }, {
  479. key: '_setupModuleMutations',
  480. value: function _setupModuleMutations(updatedModules) {
  481. var modules = this._modules;
  482. Object.keys(updatedModules).forEach(function (key) {
  483. modules[key] = updatedModules[key];
  484. });
  485. var updatedMutations = this._createModuleMutations(modules, []);
  486. this._mutations = mergeObjects([this._rootMutations].concat(toConsumableArray(updatedMutations)));
  487. }
  488. /**
  489. * Helper method for _setupModuleMutations.
  490. * The method retrieve nested sub modules and
  491. * bind each mutations to its sub tree recursively.
  492. *
  493. * @param {Object} modules
  494. * @param {Array<String>} nestedKeys
  495. * @return {Array<Object>}
  496. */
  497. }, {
  498. key: '_createModuleMutations',
  499. value: function _createModuleMutations(modules, nestedKeys) {
  500. var _this5 = this;
  501. if (!isObject(modules)) return [];
  502. return Object.keys(modules).map(function (key) {
  503. var module = modules[key];
  504. var newNestedKeys = nestedKeys.concat(key);
  505. // retrieve nested modules
  506. var nestedMutations = _this5._createModuleMutations(module.modules, newNestedKeys);
  507. if (!module || !module.mutations) {
  508. return mergeObjects(nestedMutations);
  509. }
  510. // bind mutations to sub state tree
  511. var mutations = {};
  512. Object.keys(module.mutations).forEach(function (name) {
  513. var original = module.mutations[name];
  514. mutations[name] = function (state) {
  515. for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  516. args[_key3 - 1] = arguments[_key3];
  517. }
  518. original.apply(undefined, [getNestedState(state, newNestedKeys)].concat(args));
  519. };
  520. });
  521. // merge mutations of this module and nested modules
  522. return mergeObjects([mutations].concat(toConsumableArray(nestedMutations)));
  523. });
  524. }
  525. /**
  526. * Setup mutation check: if the vuex instance's state is mutated
  527. * outside of a mutation handler, we throw en error. This effectively
  528. * enforces all mutations to the state to be trackable and hot-reloadble.
  529. * However, this comes at a run time cost since we are doing a deep
  530. * watch on the entire state tree, so it is only enalbed with the
  531. * strict option is set to true.
  532. */
  533. }, {
  534. key: '_setupMutationCheck',
  535. value: function _setupMutationCheck() {
  536. var _this6 = this;
  537. var Watcher = getWatcher(this._vm);
  538. /* eslint-disable no-new */
  539. new Watcher(this._vm, 'state', function () {
  540. if (!_this6._dispatching) {
  541. throw new Error('[vuex] Do not mutate vuex store state outside mutation handlers.');
  542. }
  543. }, { deep: true, sync: true });
  544. /* eslint-enable no-new */
  545. }
  546. }, {
  547. key: 'state',
  548. get: function get() {
  549. return this._vm.state;
  550. },
  551. set: function set(v) {
  552. throw new Error('[vuex] Use store.replaceState() to explicit replace store state.');
  553. }
  554. }]);
  555. return Store;
  556. }();
  557. function install(_Vue) {
  558. if (Vue) {
  559. console.warn('[vuex] already installed. Vue.use(Vuex) should be called only once.');
  560. return;
  561. }
  562. Vue = _Vue;
  563. override(Vue);
  564. }
  565. // auto install in dist mode
  566. if (typeof window !== 'undefined' && window.Vue) {
  567. install(window.Vue);
  568. }
  569. var index = {
  570. Store: Store,
  571. install: install
  572. };
  573. return index;
  574. }));