【问题标题】:vuejs 2.0 components failed to access action methods with module vuexvuejs 2.0 组件无法使用模块 vuex 访问操作方法
【发布时间】:2017-01-28 02:10:55
【问题描述】:

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

提前致谢!

【问题讨论】:

  • 无法访问操作方法是什么意思?您希望如何访问它们?

标签: javascript vue.js vuex


【解决方案1】:

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

在你的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

【讨论】:

  • 它不会改变任何东西。我已经这样做了,所以我在问题中添加了商店创建代码。谢谢
  • 那么您能否更新您的问题,因为您无法看到您想要如何调用您的操作或您遇到的错误是什么
猜你喜欢
  • 2017-11-20
  • 2019-10-18
  • 1970-01-01
  • 2021-10-02
  • 2017-10-01
  • 2020-02-13
  • 2018-04-25
  • 2021-12-29
  • 2021-03-28
相关资源
最近更新 更多