zoukankan      html  css  js  c++  java
  • [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
    };
  • 相关阅读:
    使用xdebug调试PHP程序
    删除有序数组中的重复元素
    libmysql.dll与php.ini是否真的要拷贝到c:\windows目录下呢
    C++中的纯虚方法
    排序算法:堆排序算法实现及分析
    虚拟蜜罐honeyd安装使用
    软件目录结构规范(以python为例)
    python源码为何都是pass
    对类的实例直接赋值
    Path Analyzer Pro出现raw socket问题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10784633.html
Copyright © 2011-2022 走看看