store.js 1.3 KB

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