1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- export const mapState = normalizeNamespace((namespace, states) => {
- const res = {}
- normalizeMap(states).forEach(({ key, val }) => {
- res[key] = function mappedState () {
- let state = this.$store.state
- let getters = this.$store.getters
- if (namespace) {
- const module = this.$store._modulesNamespaceMap[namespace]
- if (!module) {
- warnNamespace('mapState', namespace)
- return
- }
- state = module.context.state
- getters = module.context.getters
- }
- return typeof val === 'function'
- ? val.call(this, state, getters)
- : state[val]
- }
- })
- return res
- })
- export const mapMutations = normalizeNamespace((namespace, mutations) => {
- const res = {}
- normalizeMap(mutations).forEach(({ key, val }) => {
- val = namespace + val
- res[key] = function mappedMutation (...args) {
- return this.$store.commit.apply(this.$store, [val].concat(args))
- }
- })
- return res
- })
- export const mapGetters = normalizeNamespace((namespace, getters) => {
- const res = {}
- normalizeMap(getters).forEach(({ key, val }) => {
- val = namespace + val
- res[key] = function mappedGetter () {
- if (!(val in this.$store.getters)) {
- console.error(`[vuex] unknown getter: ${val}`)
- }
- return this.$store.getters[val]
- }
- })
- return res
- })
- export const mapActions = normalizeNamespace((namespace, actions) => {
- const res = {}
- normalizeMap(actions).forEach(({ key, val }) => {
- val = namespace + val
- res[key] = function mappedAction (...args) {
- return this.$store.dispatch.apply(this.$store, [val].concat(args))
- }
- })
- return res
- })
- function normalizeMap (map) {
- return Array.isArray(map)
- ? map.map(key => ({ key, val: key }))
- : Object.keys(map).map(key => ({ key, val: map[key] }))
- }
- function normalizeNamespace (fn) {
- return (namespace, map) => {
- if (typeof namespace !== 'string') {
- map = namespace
- namespace = ''
- } else if (namespace.charAt(namespace.length - 1) !== '/') {
- namespace += '/'
- }
- return fn(namespace, map)
- }
- }
- function warnNamespace (helper, namespace) {
- console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
- }
|