Vuex文件拆分

store文件下目录

index.ts
state.ts
mutation-types.ts
mutations.ts
getters.ts
actions.ts

文件

index.ts

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

state.ts(唯一数据源,包含全部应用层级的状态)

/* 优先从本地获取 */
let user = localStorage['user'];
/* 共享数据 */
const state = {
    name:"测试",
    count:1,
    user: user ? JSON.parse(user) : { name: '个人中心'},
    list: {},
}
export default state;

mutation-types.ts(定义常量暴露出去)

export const SET_ADD_COUNT = 'SET_ADD_COUNT'
export const SET_REMOVE_COUNT = 'SET_REMOVE_COUNT'

mutations.ts(提交 mutation,更改 Vuex 的 state 中的数据状态,接收state作为第一个参数)

import * as TYPES from './mutation-types'
const mutations = {
    [TYPES.SET_ADD_COUNT](state: { count: number; },data: number){
        if(data){
            state.count += data;
        }else{
            state.count++;
        }
    },
    [TYPES.SET_REMOVE_COUNT](state: { count: number; },data: number){
        if(data){
            state.count -= data;
        }else{
            state.count--;
        }
    }
}
export default mutations;

getters.ts(从store 中的 state 中派生出一些状态 ,暴露为 store.getters 对象)

const getters = {
    _user:function(state: { user: any; }){
        return state.user;
    },
    _list: function(state: { list: any; }){
        return state.list
    },
    _getCount:function(state: { count: number; }){
        return state.count + 10;
    }
}

export default getters;

actions.ts(Action 提交 mutation,执行异步操作)

import * as TYPES from './mutation-types'

const actions = {
    [TYPES.SET_ADD_COUNT](context: { commit: (arg0: string, arg1: any) => void; },val: any){
        context.commit(TYPES.SET_ADD_COUNT,val);
    },
    [TYPES.SET_REMOVE_COUNT](context: { commit: (arg0: string, arg1: any) => void; },val: any){
        context.commit(TYPES.SET_REMOVE_COUNT,val);
    }
}

export default actions;

页面引入




_20200401140837.png

你可能感兴趣的:(Vuex文件拆分)