我正在使用模块设计测试 Vuejs 2.0 和 Vuex,但组件无法访问操作方法。
我的组件:
import {mapGetters, mapActions} from 'vuex'
export default {
computed: mapGetters({
clients: 'clients',
fields: 'fields'
}),
methods: mapActions({
init: 'init'
}),
created: () => {
console.log(this.init)
}
}
我的模块:
const state = {
'fields': [
{
'field': 'name',
'label': 'Nom'
},
{
'field': 'adresse',
'label': 'Adresse'
},
{
'field': 'amount',
'label': 'Amount'
},
{
'field': 'contact',
'label': 'Contact'
}
],
items : []
}
export const SET_CLIENTS = 'SET_CLIENTS'
const mutations = {
[SET_CLIENTS] (state, clients) {
state.items = clients;
}
}
const actions = {
init: ({ commit }, payload) => {
let clients = []
for(let i = 0; i < 100; i++){
clients.push({
'name': 'Client '+i,
'adresse': '14000 Caen',
'amount': '1000',
'contact': 'contact@client'+i+'.com'
})
}
commit(SET_CLIENTS, { clients })
}
}
const getters = {
clients (state) {
return state.items;
},
fields (state) {
return state.fields;
}
}
export default {
state,
mutations,
getters,
actions
}
商店创建:
import Vuex from 'vuex'
import clients from './modules/clients'
import filters from './modules/filters'
import Vue from 'vue'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
clients,
filters
}
})
所有项目代码都可以在这里找到:https ://github.com/robynico/vuejs-2.0-modules
如果你测试它,你会看到在组件创建时 init 方法是未定义的。
提前致谢!