vuex 2.0组件无法使用模块vuex访问操作方法

vuejs 2.0 components failed to access action methods with module vuex

本文关键字:vuex 模块 访问 操作方法 组件      更新时间:2023-09-26

我正在测试Vuejs 2.0 &Vuex与模块设计,但组件不能访问操作方法。

my component:

import {mapGetters, mapActions} from 'vuex'
export default {
  computed: mapGetters({ 
    clients: 'clients',
    fields: 'fields'
  }),
  methods: mapActions({ 
    init: 'init'
  }),
  created: () => {
    console.log(this.init)
  }
}

my module:

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方法在组件创建时是未定义的。

提前感谢!

我认为你出口你的商店模块错误。试试这个:

Inside your 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