我已经注册了vuex模块,并创建了此函数this.$store.registerModule(this.name, 'some_module')
模块,但在vuedevtools中显示为空。
并且我正在尝试使用此代码this.$store.dispatch(this.name+'/some_action', this.id)
调度此返回错误未知操作类型
请帮助任何人如何动态创建vuex模块。
存储index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// Load store modules dynamically.
const requireContext = require.context('./modules', false, /.*\.js$/)
const modules = requireContext.keys()
.map(file =>
[file.replace(/(^.\/)|(\.js$)/g, ''), requireContext(file)]
)
.reduce((modules, [name, module]) => {
if (module.namespaced === undefined) {
module.namespaced = true
}
return { ...modules, [name]: module }
}, {})
export default new Vuex.Store({
modules
})
somo_module.js
import Vue from 'vue'
import axios from 'axios'
import * as types from '../mutation-types'
// state
export const state = {
count: ''
}
// getters
export const getters = {
count: state => state.count
}
// mutations
export const mutations = {
[types.GET_COUNT] (state, data ) {
state.count = data
}
}
// actions
export const actions = {
async some_action ({ commit }, payload) {
try {
const { data } = await axios.post('/count/'+payload)
commit(types.GET_COUNT, data )
// console.log(data)
} catch (e) {
}
}
}
答案 0 :(得分:0)
首先,您必须确保 this.name!== undefined ,然后才能将模块动态添加到商店中(根据DOC和{{3} })
this.$store.registerModule(this.name, {
namespaced: true,
state: {
some_items: []
},
getters: {
items: state => state.some_items
},
actions: {
someAction () {}
},
mutations: {}
})
并像往常一样this.$store.dispatch('yourModule/someAction')
如果您愿意,还可以像这样更新 store index.js ,以便将默认情况下已导出的模块注册为对象
myModule.js
const state = {}
const actions = {}
const getters = {}
const mutations = {}
const module = {
namespaced: true,
state,
getters,
mutations,
actions
}
export default module
存储index.js
如下所示,我仅对 reduce 方法
进行了少量更改import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// Load store modules dynamically.
const requireContext = require.context('./modules', false, /.*\.js$/)
const modules = requireContext.keys()
.map(file =>
[file.replace(/(^.\/)|(\.js$)/g, ''), requireContext(file)]
)
.reduce((modules, [name, mod]) => {
let module = mod.default || mod
if (module.namespaced === undefined) {
module.namespaced = true
}
return { ...modules, [name]: module }
}, {})
export default new Vuex.Store({
modules
})