helpers.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import { isObject } from './util'
  2. /**
  3. * Reduce the code which written in Vue.js for getting the state.
  4. * @param {String} [namespace] - Module's namespace
  5. * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
  6. * @param {Object}
  7. */
  8. export const mapState = normalizeNamespace((namespace, states) => {
  9. const res = {}
  10. if (__DEV__ && !isValidMap(states)) {
  11. console.error('[vuex] mapState: mapper parameter must be either an Array or an Object')
  12. }
  13. normalizeMap(states).forEach(({ key, val }) => {
  14. res[key] = function mappedState () {
  15. let state = this.$store.state
  16. let getters = this.$store.getters
  17. if (namespace) {
  18. const module = getModuleByNamespace(this.$store, 'mapState', namespace)
  19. if (!module) {
  20. return
  21. }
  22. state = module.context.state
  23. getters = module.context.getters
  24. }
  25. return typeof val === 'function'
  26. ? val.call(this, state, getters)
  27. : state[val]
  28. }
  29. // mark vuex getter for devtools
  30. res[key].vuex = true
  31. })
  32. return res
  33. })
  34. /**
  35. * Reduce the code which written in Vue.js for committing the mutation
  36. * @param {String} [namespace] - Module's namespace
  37. * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  38. * @return {Object}
  39. */
  40. export const mapMutations = normalizeNamespace((namespace, mutations) => {
  41. const res = {}
  42. if (__DEV__ && !isValidMap(mutations)) {
  43. console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object')
  44. }
  45. normalizeMap(mutations).forEach(({ key, val }) => {
  46. res[key] = function mappedMutation (...args) {
  47. // Get the commit method from store
  48. let commit = this.$store.commit
  49. if (namespace) {
  50. const module = getModuleByNamespace(this.$store, 'mapMutations', namespace)
  51. if (!module) {
  52. return
  53. }
  54. commit = module.context.commit
  55. }
  56. return typeof val === 'function'
  57. ? val.apply(this, [commit].concat(args))
  58. : commit.apply(this.$store, [val].concat(args))
  59. }
  60. })
  61. return res
  62. })
  63. /**
  64. * Reduce the code which written in Vue.js for getting the getters
  65. * @param {String} [namespace] - Module's namespace
  66. * @param {Object|Array} getters
  67. * @return {Object}
  68. */
  69. export const mapGetters = normalizeNamespace((namespace, getters) => {
  70. const res = {}
  71. if (__DEV__ && !isValidMap(getters)) {
  72. console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object')
  73. }
  74. normalizeMap(getters).forEach(({ key, val }) => {
  75. // The namespace has been mutated by normalizeNamespace
  76. val = namespace + val
  77. res[key] = function mappedGetter () {
  78. if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
  79. return
  80. }
  81. if (__DEV__ && !(val in this.$store.getters)) {
  82. console.error(`[vuex] unknown getter: ${val}`)
  83. return
  84. }
  85. return this.$store.getters[val]
  86. }
  87. // mark vuex getter for devtools
  88. res[key].vuex = true
  89. })
  90. return res
  91. })
  92. /**
  93. * Reduce the code which written in Vue.js for dispatch the action
  94. * @param {String} [namespace] - Module's namespace
  95. * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
  96. * @return {Object}
  97. */
  98. export const mapActions = normalizeNamespace((namespace, actions) => {
  99. const res = {}
  100. if (__DEV__ && !isValidMap(actions)) {
  101. console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object')
  102. }
  103. normalizeMap(actions).forEach(({ key, val }) => {
  104. res[key] = function mappedAction (...args) {
  105. // get dispatch function from store
  106. let dispatch = this.$store.dispatch
  107. if (namespace) {
  108. const module = getModuleByNamespace(this.$store, 'mapActions', namespace)
  109. if (!module) {
  110. return
  111. }
  112. dispatch = module.context.dispatch
  113. }
  114. return typeof val === 'function'
  115. ? val.apply(this, [dispatch].concat(args))
  116. : dispatch.apply(this.$store, [val].concat(args))
  117. }
  118. })
  119. return res
  120. })
  121. /**
  122. * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
  123. * @param {String} namespace
  124. * @return {Object}
  125. */
  126. export const createNamespacedHelpers = (namespace) => ({
  127. mapState: mapState.bind(null, namespace),
  128. mapGetters: mapGetters.bind(null, namespace),
  129. mapMutations: mapMutations.bind(null, namespace),
  130. mapActions: mapActions.bind(null, namespace)
  131. })
  132. /**
  133. * Normalize the map
  134. * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
  135. * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
  136. * @param {Array|Object} map
  137. * @return {Object}
  138. */
  139. function normalizeMap (map) {
  140. if (!isValidMap(map)) {
  141. return []
  142. }
  143. return Array.isArray(map)
  144. ? map.map(key => ({ key, val: key }))
  145. : Object.keys(map).map(key => ({ key, val: map[key] }))
  146. }
  147. /**
  148. * Validate whether given map is valid or not
  149. * @param {*} map
  150. * @return {Boolean}
  151. */
  152. function isValidMap (map) {
  153. return Array.isArray(map) || isObject(map)
  154. }
  155. /**
  156. * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
  157. * @param {Function} fn
  158. * @return {Function}
  159. */
  160. function normalizeNamespace (fn) {
  161. return (namespace, map) => {
  162. if (typeof namespace !== 'string') {
  163. map = namespace
  164. namespace = ''
  165. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  166. namespace += '/'
  167. }
  168. return fn(namespace, map)
  169. }
  170. }
  171. /**
  172. * Search a special module from store by namespace. if module not exist, print error message.
  173. * @param {Object} store
  174. * @param {String} helper
  175. * @param {String} namespace
  176. * @return {Object}
  177. */
  178. function getModuleByNamespace (store, helper, namespace) {
  179. const module = store._modulesNamespaceMap[namespace]
  180. if (__DEV__ && !module) {
  181. console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
  182. }
  183. return module
  184. }