store.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import Vue from 'vue'
  2. import Vuex from '../../src'
  3. Vue.use(Vuex)
  4. // mutation types
  5. // optional if you don't like constants.
  6. const INCREMENT = 'INCREMENT'
  7. const DECREMENT = 'DECREMENT'
  8. // root state object.
  9. // each Vuex instance is just a single state tree.
  10. const state = {
  11. count: 0
  12. }
  13. // actions are what components will be able to
  14. // call as store.actions.xxx
  15. // note these are not the final functions the
  16. // components will be calling.
  17. const actions = {
  18. // for simple actions that just dispatches a single mutation,
  19. // we can just provide the mutation type.
  20. increment: INCREMENT,
  21. decrement: DECREMENT,
  22. // for a normal action function, it always recieves the store
  23. // instance as the first argument, from which we can get the
  24. // dispatch function and the state object. Any additional
  25. // arguments will follow the store argument.
  26. incrementIfOdd: ({ dispatch, state }) => {
  27. if ((state.count + 1) % 2 === 0) {
  28. dispatch(INCREMENT)
  29. }
  30. },
  31. // Same thing for async actions.
  32. incrementAsync: ({ dispatch }) => {
  33. setTimeout(() => {
  34. dispatch(INCREMENT)
  35. }, 1000)
  36. }
  37. }
  38. // mutations are operations that actually mutates the state.
  39. // each mutation handler gets the entire state tree as the
  40. // first argument, followed by additional payload arguments.
  41. // mutations must be synchronous and can be recorded by middlewares
  42. // for debugging purposes.
  43. const mutations = {
  44. [INCREMENT] (state) {
  45. state.count++
  46. },
  47. [DECREMENT] (state) {
  48. state.count--
  49. }
  50. }
  51. // A Vuex instance is created by combining the state, the actions,
  52. // and the mutations. Because the actions and mutations are just
  53. // functions that do not depend on the instance itself, they can
  54. // be easily tested or even hot-reloaded (see counter-hot example).
  55. //
  56. // You can also provide middlewares, which is just an array of
  57. // objects containing some hooks to be called at initialization
  58. // and after each mutation.
  59. export default new Vuex.Store({
  60. state,
  61. actions,
  62. mutations
  63. })