3

我正在使用模块设计测试 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 方法是未定义的。

提前致谢!

4

1 回答 1

2

我认为您错误地导出了商店模块。尝试这个:

在你的内部module.js

export default {
  state: {},  // define your state here
  getter: {},  // define your getters here
  actions: {}, // define your actions here
  mutations: {} // define your mutations here
}

然后在您的商店内:

import Vue from 'vue'
import Vuex from 'vuex'

import module from './modules/module.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    module // your moudle
  }
})

export default store
于 2016-09-20T09:00:24.387 回答