我正在用vue + vuex创建一个简单的spa todo应用程序。
我的问题是每个模块都有相同的5种默认方法来操纵状态。如果我决定更改默认状态管理行为,那么我必须转到每个模块并更新它们。在模块中写出时所有模块应该具有的五个动作,但是只要我导入完全相同的对象并将其分配给模块上的actions属性,就无法找到动作。我得到这个错误[vuex]未知的动作类型:namespacedTodos / getCollection
// This is in a component
mounted: function () {
this.$store.dispatch('namespacedTodos/getCollection')
},

// import baseActions from '../base-actions'
import baseGetters from '../base-getters'
import baseMutations from '../base-mutations'
import axios from 'axios/index'
import mainStore from '../index'
// import _ from 'lodash'
const namespacedTodos = {
namespaced: true,
state: {
collection: [],
defaultInstance: {},
collectionLoaded: false,
url: 'api/todos',
namespace: 'namespacedTodos'
},
mutations: baseMutations,
getters: baseGetters,
actions: {
getCollection: function ({state, commit}) {
if (state.collectionLoaded) {
return Promise.resolve({data: state.collection})
}
return axios.get(`${mainStore.state.baseUrl}/${state.url}`)
.then((response) => {
commit(`setCollection`, response.data.data)
return response
})
.catch((response) => {
console.log('Error Response: ', response)
throw response
})
}
},
strict: process.env.NODE_ENV !== 'production'
}
export default namespacedTodos

以上代码有效,但以下剂量不
import baseActions from '../base-actions'
import baseGetters from '../base-getters'
import baseMutations from '../base-mutations'
const namespacedTodos = {
namespaced: true,
state: {
collection: [],
defaultInstance: {},
collectionLoaded: false,
url: 'api/todos',
namespace: 'namespacedTodos'
},
mutations: baseMutations,
getters: baseGetters,
actions: baseActions,
strict: process.env.NODE_ENV !== 'production'
}
export default namespacedTodos

import axios from 'axios'
import _ from 'lodash'
import mainStore from './index'
export default {
getCollection: function ({state, commit}) {
if (state.collectionLoaded) {
return Promise.resolve({data: state.collection})
}
console.log('this: ', this)
console.log('Namespace: ', state.namespace)
return axios.get(`${mainStore.state.baseUrl}/${state.url}`)
.then((response) => {
commit(`setCollection`, response.data.data)
return response
})
.catch((response) => {
console.log('Error Response: ', response)
throw response
})
},
}

答案 0 :(得分:1)
import baseActions from '../base-actions'
import baseGetters from '../base-getters'
import baseMutations from '../base-mutations'
const todos = {
namespaced: true,
state: {
collection: [],
defaultInstance: {},
collectionLoaded: false,
url: 'api/todos'
},
// The mutations get namespaced!!
mutations: Object.assign(baseMutations, {}),
// The getters get namespaced!!
getters: Object.assign(baseGetters, {}),
// The actions get namespaced!!
actions: Object.assign(baseActions, {
// any methods defined here will also be available
// You can over write existing methods when nessicary
}),
strict: process.env.NODE_ENV !== 'production'
}
export default todos