typescript下的vuex怎么用?再不知道就晚了

ts配置vuex的使用指南

在使用vue-cli3和typescript搭建项目的大型项目的时候,因为官网文档太过于简单导致,往往会出现各种问题,今天就详细讲讲关于store仓库如何使用问题(无奈狗头,网上提供的资源过于简单不满足具体需求),在这里使用module子仓库的方式搭建vuex的store

详细讲解store在ts下多模块配置

有关于vue.config.js配置和tsconfig.json配置在这里就不多讲解了,如需要请猛戳这里

1.store目录展示

  src
  --store
  ----modules   //下面每个子仓库文件
  ======types  //子仓库的ts接口声明
  ======index.ts   //统一导出子仓库
  ======shop.ts   //子仓库1
  ======chat.ts    //子仓库2
  ----getters.ts       //统一导出所有的state
  ----index.ts         //配置vuex 
  ----mutationd-types.ts   //统一导出所有的mutation
  ----types.ts                   //定义ts接口规范 

2.index.ts 配置

import Vue from 'vue';
import Vuex, { StoreOptions } from 'vuex';
import { RootState } from './types'; //定义state的类型
import * as getters from './getters'; 
import modules from './modules';
Vue.use(Vuex);
const store: StoreOptions = {
  state: {
   anthor: 'xzl',
  },
  getters,
  modules,
};

export default new Vuex.Store(store);

3.getters.ts

export const user1 = state => state.chat.user;
export const food = state => state.shop.food;

4.mutations-types.ts

export default {
  SHOW_LOADING: 'SHOW_LOADING',
  ADD_FOOD: 'ADD_FOOD',
};

5.types.ts

export interface RootState {
  version: string;
}

6.modules下的配置

index.ts
在ts下的index和正常的配置有一点区别,正则匹配的是ts,而不是js,并且赋值的是files(key)而不是files(key).defalut

const files = require.context('.', false, /\.ts$/);
const modules = {};
files.keys().forEach((key) => {
    if (key === './index.ts') { return; }
    modules[key.replace(/(\.\/|\.ts)/g, '')] = files(key);
});
export default modules;

子仓库的写法
其中MutationTreeActionTreeGetterTree都是vuex在ts下封装好的

import types from '../mutations-types';
import { Module, ActionTree, MutationTree  } from 'vuex';
import { GlobalFood } from './types/types'; //定义state里面值的类型
import { RootState } from '../types';
export const state: GlobalFood = {
  food: '可乐',
};

export const  mutations: MutationTree = {
  [types.ADD_FOOD](state: any, payload: any): void {
    state.food = payload;
  },
};
export const  actions: ActionTree = {
 async login({commit}, payload) {
    commit(types.ADD_FOOD, payload);
  }
};
const namespaced: boolean = true;
export const shop: Module = {
  namespaced,
  state,
  mutations,
  actions
};

以上是store的用法,有不解的地方,可以访问我的githua上的demo或者下面评论我。

最后在vue里调用store


你可能感兴趣的:(typescript下的vuex怎么用?再不知道就晚了)