1
0

vuex.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 vuex.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 conditional actions that depend on the state,
  23. // we can provide a thunk (a function that returns a function)
  24. // the returned function will get two arguments,
  25. // the first being the dispatch function and the second is
  26. // the state tree.
  27. incrementIfOdd: () => (dispatch, state) => {
  28. if (state.count % 2 === 1) {
  29. dispatch(INCREMENT)
  30. }
  31. },
  32. // we also use thunks for async actions.
  33. // you can dispatch multiple mutations inside a thunk action.
  34. incrementAsync: () => dispatch => {
  35. setTimeout(() => {
  36. dispatch(INCREMENT)
  37. }, 1000)
  38. }
  39. }
  40. // mutations are operations that actually mutates the state.
  41. // each mutation handler gets the entire state tree as the
  42. // first argument, followed by additional payload arguments.
  43. // mutations must be synchronous and can be recorded by middlewares
  44. // for debugging purposes.
  45. const mutations = {
  46. [INCREMENT] (state) {
  47. state.count++
  48. },
  49. [DECREMENT] (state) {
  50. state.count--
  51. }
  52. }
  53. // A Vuex instance is created by combining the state, the actions,
  54. // and the mutations. Because the actions and mutations are just
  55. // functions that do not depend on the instance itself, they can
  56. // be easily tested.
  57. //
  58. // You can also provide middlewares, which is just an array of
  59. // objects containing before/after hooks that will get called for
  60. // each mutation.
  61. export default new Vuex({
  62. state,
  63. actions,
  64. mutations
  65. })