store.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { createStore } from 'vuex'
  2. // root state object.
  3. // each Vuex instance is just a single state tree.
  4. const state = {
  5. count: 0
  6. }
  7. // mutations are operations that actually mutate the state.
  8. // each mutation handler gets the entire state tree as the
  9. // first argument, followed by additional payload arguments.
  10. // mutations must be synchronous and can be recorded by plugins
  11. // for debugging purposes.
  12. const mutations = {
  13. increment (state) {
  14. state.count++
  15. },
  16. decrement (state) {
  17. state.count--
  18. }
  19. }
  20. // actions are functions that cause side effects and can involve
  21. // asynchronous operations.
  22. const actions = {
  23. increment: ({ commit }) => commit('increment'),
  24. decrement: ({ commit }) => commit('decrement'),
  25. incrementIfOdd ({ commit, state }) {
  26. if ((state.count + 1) % 2 === 0) {
  27. commit('increment')
  28. }
  29. },
  30. incrementAsync ({ commit }) {
  31. return new Promise((resolve, reject) => {
  32. setTimeout(() => {
  33. commit('increment')
  34. resolve()
  35. }, 1000)
  36. })
  37. }
  38. }
  39. // getters are functions.
  40. const getters = {
  41. evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
  42. }
  43. // A Vuex instance is created by combining the state, mutations, actions,
  44. // and getters.
  45. export default createStore({
  46. state,
  47. getters,
  48. actions,
  49. mutations
  50. })