This article introduces some oF the vex4 apis for TypeScript types. And write a Vue3 + TypeScript using Vex4 case.

This section describes Vuex4 apis

createStore<S>

createStoreIs used to create astoreInstance.createStoreMethod receives aStoreOptions<S>Type and return oneStore<S>. As shown below:

StoreOptions<S>

StoreOptionsIt’s a descriptionStoreThe interface contains the familiarstate,mutations,actions,getters,modules. As shown below:

state

State objects.

  • Type: object or function. If a function is passed in, the object returned by the function is usedstate

getters

Method set object to get state data.

  • Type:GetterTree<S, R>Description:getterMethod set interface
GetterTree<S, R>

describegetterMethod set interface. This interface defines the object properties that implement it asstringType and the value isGetter<S, R>Type.

Getter<S, R>

The type that describes the format of the getter method. The parameters and return values of the method are as follows

  • Parameters:state: S, getters: any, rootState: R, rootGetters: any
  • The return value:any

mutations

Change the method set object for state.

  • Type:MutationTree<S>: describes the change method set interface
MutationTree<S>

Describes the change method set interface.

Mutation<S>

Describes the type of change method format. The parameters and return values of the method are as follows

  • Parameters:state: S, payload? : any
  • The return value:any

actions

Actions is similar to mutations, except that the methods in mutations are synchronous, while the methods in Actions can be asynchronous.

The Action commits mutation rather than a direct state change.

  • Type:ActionTree<S, S>Description:actionMethod set interface
ActionTree<S, S>

Describes the Action method set interface.

Action<S, R>

Action<S, R>Can be eitherActionHandler<S, R>Type, which can also beActionObject<S, R>type

ActionHandler<S, R>andActionObject<S, R>The type definition is as follows:

modules

Place objects for the Store module

  • Type:ModuleTree<R>
ModuleTree<R>

describeModuleObject set interface

Module<any, R>

Describes the interface of a module

Demo

This Demo includes managing user information in the main file and dictionaries in the dictionary module

Store/index. Ts file. Store /index.ts Manages the state of user information as follows:

import { createStore } from "vuex";
import { getUserInfoById } from "@/api/user";  // Initiate a request to obtain user information
import DictStoreModule from "./modules/DictStore";

interface IUserInfo {
  id: string;
  name: string;
  sex: string;
  birtyDay: Date;
}

interface IUserIngoStore {
  [key: string]: IUserInfo | undefined;
}

const userInfo: IUserInfo | undefined = undefined;

export default createStore<IUserIngoStore>({
  state: { userInfo },
  getters: {
    RootGetters, rootState, and rootGetters are not needed
    getUserInfo: (state): IUserInfo | undefined= > {
      returnstate.userInfo; }},mutations: {
    setUserInfo(state, payload: IUserInfo): void {
      state.userInfo = payload;
    },
    delUserInfo(state): void {
      state.userInfo = undefined; }},actions: {
    fetchUserInfo: async (context, payload: string) :Promise<void> = > {const userInfoData = await getUserInfoById(payload);
      context.commit("setUserInfo", userInfoData); }},modules: { DictStoreModule },
});

Copy the code

Store/modules/DictStore ts management state of the dictionary, the content is as follows:

import { getDictByName } from "@/api/dict";
import { Module } from "vuex";

export interface IDictItem {
  id: string;
  lable: string;
  value: string | number | boolean;
}

export const dicts = new Map<string, IDictItem[]>();

dicts.set("sex"[{id: "1".lable: "Male".value: "1" },
  { id: "2".lable: "Female".value: "2"},]);interface IDict {
  [key: string] :Map<string, IDictItem[]>;
}

const DictStoreModule: Module<IDict, any> = {
  state: { dicts },
  getters: {
    getDict:
      (state) = >
      (key: string): IDictItem[] | undefined= > {
        const dict = state.dicts.get(key);
        returndict; }},mutations: {
    setDict(state, payload: Map<string, IDictItem[]>): void {
      payload.forEach((v, k) = > {
        state.dicts.set(k, v);
      });
    },
    delDict(state, payload: string) :boolean {
      return state.dicts.delete(payload);
    },
    clearAll(state: IDict): void {
      returnstate.dicts.clear(); }},actions: {
    fetchDict: async (context, payload: string) :Promise<void> = > {const data = await getDictByName(payload);
      const dict = new Map<string, IDictItem[]>();
      dict.set(payload, data);
      context.commit("setDict", dict); ,}}};export default DictStoreModule;

Copy the code

use

The store can be accessed from the Setup hook function by calling the useStore function in Vue3’s composite API. This is equivalent to accessing this.$store in a component using the optional API.

import { useStore } from "vuex";

const store = useStore();
// Calls the getDict method defined in getters of the dictionary module
constDictData = store. Getters. GetDict method (dictName);Copy the code

Global registration method

Write a method that calls the dictionary store and mixes it globally so that it can be called directly when used.

  1. Write plug-ins, mixing in the methods you write
import { IDictItem } from "@/store/modules/DictStore";
import { App } from "vue";
import { useStore } from "vuex";

const DictInstall = {
  install: (app: App): App<any> => {
    app.mixin({
      methods: {
        dictData: (dictName: string): IDictItem[] | undefined= > {
          const store = useStore();
          const dictData = store.getters.getDict(dictName);
          if(! dictData) { store.dispatch("fetchDict", dictName);
          }
          return dictData;
        },
        dictDataLable: (
          dictName: string.dictValue: string | number | boolean) :string | undefined= > {
          const store = useStore();
          const dictData = store.getters.getDict(dictName);
          if(! dictData) { store.dispatch("fetchDict", dictName);
          }
          if (dictData) {
            const dictItem = dictData.find(
              (d: IDictItem) = > d.value === dictValue
            );
            if (dictItem) {
              returndictItem.lable; }}return undefined; ,}}});returnapp; }};export default DictInstall;

Copy the code
  1. Globally registered plug-in
import DictInstall from "./plugins/DictPlugin";

const app = createApp(App);
app.use(DictInstall).use(store).use(router).use(Antd).mount("#app");
Copy the code
  1. Use the global blend method
<template>
  <div>dict: {{ dictData("sex") }}</div>
  <div>dictLable: {{ dictDataLable("sex", "1") }}</div>
</template>

<script setup ts>
</script>

<style lang="scss" scoped></style>
Copy the code
  1. The effect