For those of you who have used Vue, vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application, and rules to ensure that the state changes in a predictable manner. To put it simply, the state of VUE is managed in a unified manner. The following figure describes its management mode:

The simplest way to use it looks like this:

// If in a modular build system, be sure to call vue.use (Vuex) at the beginning

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
Copy the code

If you have a lot of state to manage in your project, you can also separate these methods into files and mount them under the index file:

// state.js
export default {
    total: 0
}
Copy the code
// mutaction.js
export default {
    add(state){
      state++
  }
}
Copy the code
// action.js
export default {
    addAsync(context){
     setTimeout((a)= > {
            context.commit('add');
     }, 1000); }}Copy the code

Finally, import it into index.js

// index.js
import Vue from 'vue';
import Vuex from 'vuex';
import { state } from './state';
import mutations from './mutation';
import actions from './action';

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  mutations,
  actions,
});
Copy the code

Over, this is the basic vuEX development model. I’m not going to talk too much about vuex. Instead, I’m going to talk about how to use vue and Vuex in typescript as a class for projects.

In order to save some configuration trouble, we directly used Vue-CLI3 to build the project. Just select typescript when you create the project.

After creating the project, we adjusted the project structure to make it easier to maintain and manage, as follows:

export interface State {
    name: string;
    total: number;
    isLogin: boolean;
    postList: object[];
}

export const state: State = {
    name: ' '.total: 0.isLogin: false.postList: [],};Copy the code

For those of you unfamiliar with typescript, go to the typescript website for basic usage.

The action file is the same as before, except that the type definition and parameters are added:

export default {
    asyncAdd(context: any, paylod: any) {
        setTimeout((a)= > {
            context.commit('add', paylod.num);
        }, 1000); }};Copy the code

Here is the mutaction file:

import { State } from './state';

export default {
    add(state: State, payload: any) { payload ? (state.total += payload) : state.total++; }};Copy the code

At this point, it is important to briefly explain the difference between action and mutAction: Action is similar to mutation in that:

  • The Action commits the mutation instead of directly changing the state.
  • An Action can contain any asynchronous operation. The simple point is that mutation is used for synchronous execution, and action is used for asynchronous execution, and multiple distributions of mutations can be made.

With that done, the work of Vuex is largely in the paragraphs, and we’ll focus on the page components and how to use vuex in them.

// home.vue
<template>
  <div class="home">
    <img alt="Vue logo" src=".. /assets/logo.png">
    <HelloWorld :msg="name" />
    <div @click="onclick">{{name}}</div>
    <div @click="add">Sync to increase total: {{total}}</div>
    <div @click="addAsync(1)">Increase total number asynchronously: {{total}}</div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { mapMutations } from 'vuex';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src

@Component({
  components: {
    HelloWorld,
  },
})
export default class Home extends Vue {
  public name: string = 'xujiang';

  public onclick(): void {
    this.name = 'hello world';
  }

  public add() {
    this.$store.commit('add');
  }

  public addAsync(num: any) {
    this.$store.dispatch('asyncAdd', {num});
  }

  get total(): void {
    return this.$store.state.total; }}</script>
Copy the code

I believe those who have used React are not unfamiliar with this writing method. In fact, VUE can completely rewrite the template writing method into JSX, just like writing JSX files of React. I will publish an article later, which will introduce how to develop VUE components using JSX +class. Vue-cli3 has installed a vue-property-decorator module that supports classes and decorators. If you want to configure it yourself, you can also configure it with WebPack. Teach you how to play with webpack4.0.

We define data as the data source. In class, we can define attributes directly, which can be used as initial data. 2. Vue instance methods are generally defined in methods. When using class components, you can directly use component methods. Finally, we can use the commit and Dispatch provided by Vuex to trigger a change in our state. At this point, a class version of vue is written. If you want to learn more about front-end knowledge and exchange front-end experience, please join our learning exchange group.

3. React +redux+ Trunk +immutable