【问题标题】:How to break Vuex into modules如何将 Vuex 分解为模块
【发布时间】:2021-01-31 18:00:51
【问题描述】:

我试图将状态、getter、动作和突变分离到特定模块中的单独文件中。好吧,我已经尝试过,但无法弄清楚下面的错误来自哪里或如何解决它。

错误

这是应用结构

这是我所做的:

在actions.js中

import axios from 'axios'

const actions  = {
    async getTodos(){
        let page_url = 'https://jsonplaceholder.typicode.com/todos';
        const res = await axios.get(page_url);
        console.log(res.data);
        this.commit('ALL_TODOS', res.data)
    }
}

export {
    actions
}

在 getters.js 中

const allTodos = (state) => state.todos

export default {
    allTodos
}

在 mutation.js 中

const ALL_TODOS = (state, payload) => state.todos = payload

export {
    ALL_TODOS
}

在 state.js 中

const state = {
    todos: []
}

export {
    state
}

我的意图是将所有这些文件导入到 todo 文件夹store/todo/index.js 内的一个 index.js 文件中。

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

import state from './state';
import getters from './getters';
import actions from './actions';
import mutations from './mutations';

Vue.use(Vuex);

export const store1 = new Vuex.Store({
    state,
    actions,
    getters,
    mutations,
  });

完成此操作后,我希望我创建的所有商店都可以在 store/index.js 文件中使用,就像这样

import Todos from './modules/todo/index';

export default {
    Todos
}

这样,我必须在 js/main.js 中导入的只是 store/index.js,就像我在下面的行中所做的那样

import store from './store/index';

【问题讨论】:

  • 我感觉问题与不正确的导出有关。尝试删除export { actions }actions 周围的括号并将其替换为export default actions。也可以使用 state.js 中的 state 执行此操作,并尝试在 mutation.js 中的 export 之后添加 default。如果你能创建一个codesandbox 来演示这个问题,它会更容易帮助你
  • @marsnebulasoup 完全正确,我将 export 更改为 export default {} 并且它有效,除了承诺返回 undefined
  • 你的意思是actions?你没有返回任何东西,所以它会返回 undefined...
  • 是的,但console.log(res.data) 应该显示我猜的响应?
  • 是的,但console.log(res.data) 应该显示我猜的响应?

标签: javascript vue.js vuex vuex-modules


【解决方案1】:

在 vuex 中,所有操作都接受参数“上下文”并从中调用提交。 请在https://vuex.vuejs.org/guide/actions.html#dispatching-actions查看文档

【讨论】:

  • @courage 请回复此答案。
猜你喜欢
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 2021-02-26
相关资源
最近更新 更多