helpers.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. export const mapState = normalizeNamespace((namespace, states) => {
  2. const res = {}
  3. normalizeMap(states).forEach(({ key, val }) => {
  4. res[key] = function mappedState () {
  5. let state = this.$store.state
  6. let getters = this.$store.getters
  7. if (namespace) {
  8. const module = this.$store._modulesNamespaceMap[namespace]
  9. if (!module) {
  10. warnNamespace('mapState', namespace)
  11. return
  12. }
  13. state = module.context.state
  14. getters = module.context.getters
  15. }
  16. return typeof val === 'function'
  17. ? val.call(this, state, getters)
  18. : state[val]
  19. }
  20. })
  21. return res
  22. })
  23. export const mapMutations = normalizeNamespace((namespace, mutations) => {
  24. const res = {}
  25. normalizeMap(mutations).forEach(({ key, val }) => {
  26. val = namespace + val
  27. res[key] = function mappedMutation (...args) {
  28. return this.$store.commit.apply(this.$store, [val].concat(args))
  29. }
  30. })
  31. return res
  32. })
  33. export const mapGetters = normalizeNamespace((namespace, getters) => {
  34. const res = {}
  35. normalizeMap(getters).forEach(({ key, val }) => {
  36. val = namespace + val
  37. res[key] = function mappedGetter () {
  38. if (!(val in this.$store.getters)) {
  39. console.error(`[vuex] unknown getter: ${val}`)
  40. }
  41. return this.$store.getters[val]
  42. }
  43. })
  44. return res
  45. })
  46. export const mapActions = normalizeNamespace((namespace, actions) => {
  47. const res = {}
  48. normalizeMap(actions).forEach(({ key, val }) => {
  49. val = namespace + val
  50. res[key] = function mappedAction (...args) {
  51. return this.$store.dispatch.apply(this.$store, [val].concat(args))
  52. }
  53. })
  54. return res
  55. })
  56. function normalizeMap (map) {
  57. return Array.isArray(map)
  58. ? map.map(key => ({ key, val: key }))
  59. : Object.keys(map).map(key => ({ key, val: map[key] }))
  60. }
  61. function normalizeNamespace (fn) {
  62. return (namespace, map) => {
  63. if (typeof namespace !== 'string') {
  64. map = namespace
  65. namespace = ''
  66. } else if (namespace.charAt(namespace.length - 1) !== '/') {
  67. namespace += '/'
  68. }
  69. return fn(namespace, map)
  70. }
  71. }
  72. function warnNamespace (helper, namespace) {
  73. console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
  74. }