1
0

vuex.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 can be recorded by middlewares.
  44. const mutations = {
  45. [INCREMENT] (state) {
  46. state.count++
  47. },
  48. [DECREMENT] (state) {
  49. state.count--
  50. }
  51. }
  52. // A Vuex instance is created by combining the state, the actions,
  53. // and the mutations. Because the actions and mutations are just
  54. // functions that do not depend on the instance itself, they can
  55. // be easily tested.
  56. //
  57. // You can also provide middlewares, which is just an array of
  58. // objects containing before/after hooks that will get called for
  59. // each mutation.
  60. export default new Vuex({
  61. state,
  62. actions,
  63. mutations
  64. })