Basic use of Vuex4 (Module) + Typescript

 1. Introduction to Vuex4

vuex is a state management pattern + library developed specifically for Vue.js applications. It uses a centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner. Vuex includes five core concepts: State, Getter, Mutation, Action, and Module. Reference official website: vuex official website

2. Vuex installation

//现在默认是vuex3,所以加上next安装下一个版本
npm install vuex@next

//package.json文件中,查看版本
"dependencies": {
    "vuex": "^4.0.2"
 },

3. Use of Vuex

1. Create a store object

vuex4 introduces the createStore method to create a store object. The createStore method accepts a generic type to limit the state type. Introduce modules to divide the store, and each module has its own state, mutation, action, and getter to avoid bloated store objects. Create a store object as follows and divide it into two modules: app and user.

import { createStore } from 'vuex';

// 对state的类型进行限定
export interface IRootState {
    user: IUserState;
    app: IAppState;
}

//  创建store对象
export const store = createStore<IRootState>({
    modules: {
        app,
        user,
    },
});

2. Define the module

First, vuex4 defines the module type as follows, S is the type limitation of the state in the module, and R is the type limitation of the state in the root store

export interface Module<S, R> {
     namespaced?: boolean;
     state?: S | (() => S);
     getters?: GetterTree<S, R>;
     actions?: ActionTree<S, R>;
     mutations?: MutationTree<S>;
     modules?: ModuleTree<R>;
}

Define the app module as follows

import { Module, ActionTree, GetterTree, MutationTree } from 'vuex';

const data = {};
const mutations: MutationTree<IAppState> = {};
const actions: ActionTree<IAppState, IRootState> = {};
const getters: GetterTree<IAppState, IRootState> = {};
const appModule: Module<IAppState, IRootState> = {
    state: data,
    actions,
    mutations,
    getters,
};
export default appModule;

vuex 4 introduces a new API for interacting with stores in a composite API. setup A composite function can be used in  a component's  hook function useStore to retrieve the store.

import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()
  }
}

3. Register in main.ts, so that the store object can be used in each component.

// main.ts文件中
import { createApp } from 'vue'
import store from '@/store'

const app = createApp(App)

app.use(store)

app.mount('#app')

Four. Summary

vuex4The changes in are relatively small, except for some differences in creation and acquisition, the use is exactly the same as before. It should be noted that the auxiliary function part cannot be setupused in the combined writing method. You can also refer to related articles: Basic use of vuex4 (typescript)

Guess you like

Origin blog.csdn.net/lfq1996/article/details/129792111