[Vuex] Split Vuex Store into Modules using TypeScript

When the Vuex store grows, it can have many mutations, actions and getters, belonging to different contexts.

Vuex allows you to split your store into different contexts by using modules.

In this lesson we’ll see how can we split the store in multiple Vuex modules using TypeScript

 

From the code we have before:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';

import todos, {getters, mutations, actions} from './todos';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    ...todos,
  },
  getters,
  mutations,
  actions
});
复制代码

 

To:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';

import {todos} from './todos';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    todos,
  }
});
复制代码

 

You can put 'getters, actions, mutations, state' into 'modules' which has many features as key 

modules: {
  todos: {getters, actions, state, mutations},
  login  : {getters, actions, state, mutations},
}

 

Todo store:

复制代码
import {GetterTree, MutationTree} from 'vuex';
import {State} from '../types';
import {Todo} from '../types';

const state: State = {
    todos: [
        {text: 'Buy milk', checked: false},
        {text: 'Learning', checked: true},
        {text: 'Algorithom', checked: false},
    ],
};

const getters: GetterTree<State, any> = {
    todos: state => state.todos.filter(t => !t.checked),
    dones: state => state.todos.filter(t => t.checked)
};

const mutations: MutationTree<State> = {
    addTodo(state, newTodo) {
        const copy = {
            ...newTodo
        };
        state.todos.push(copy);
    },
    toggleTodo(state, todo) {
        todo.checked = !todo.checked;
    }
};

const actions: ActionTree<tate, any> = {
    addTodoAsync(context, id) {
        fetch('https://jsonplaceholder.typicode.com/posts/'+id)
            .then(data => data.json())
            .then(item => {
                const todo: Todo = {
                    checked: false,
                    text: item.title
                }

                context.commit('addTodo', todo);
            })
    }
}

export const todos = {
    actions,
    state,
    mutations,
    getters
};
复制代码
posted @   Zhentiw  阅读(576)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-04-28 [TypeScript] Find the repeated item in an array using TypeScript
2016-04-28 [AngularJS] angular-md-table for Angular material design
2016-04-28 [Angular 2] Using a Value from the Store in a Reducer
2016-04-28 [Angular 2] Using a Reducer to Change an Object's Property Inside an Array
点击右上角即可分享
微信分享提示