Home > Web Front-end > JS Tutorial > Detailed interpretation of the management mode vuex in vue

Detailed interpretation of the management mode vuex in vue

亚连
Release: 2018-06-23 15:28:10
Original
1892 people have browsed it

This article mainly introduces the in-depth understanding of vue's state management model vuex. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor and take a look.

vuex is a state management mode specially designed for vue.js, and can also be debugged using devtools.

Note: The examples and other codes in this article will use es6 syntax.

Link

  1. vuex official Chinese website

  2. Simple mall implemented using vue and vuex, for reference only

What is vuex?

First quote from the vuex official website:

Vuex is a state management model specially developed for Vue.js applications. It uses 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 way.

State management mode and centralized storage management sound very high-end and quite scary. In my opinion, vuex stores all the variables that need to be shared in an object, and then places this object in the top-level component for use by other components. Let's put it this way, think of vue as a js file and components as functions, then vuex is a global variable, but this "global variable" contains some specific rules.

In the component development of Vue, we often encounter the need to pass the status of the current component to other components. When communicating between parent and child components, we usually use props emit. But when the communicating parties are not parent-child components or even have no relevant relationship at all, or a state needs to be shared with multiple components, it will be very troublesome and the data will be quite difficult to maintain, which is very unfriendly to our development. vuex is very practical at this time, but after using vuex, it also brings more concepts and frameworks, so you need to be careful!

What's in vuex?

Talk is cheap, Show me the code. First, here is a section of code with so many words:

const store = new Vuex.Store({
  state: {
    name: 'weish',
    age: 22
  },
  getters: {
    personInfo(state) {
      return `My name is ${state.name}, I am ${state.age}`;
    }
  }
  mutations: {
    SET_AGE(state, age) {
      commit(age, age);
    }
  },
  actions: {
    nameAsyn({commit}) {
      setTimeout(() => {
        commit('SET_AGE', 18);
      }, 1000);
    }
  },
  modules: {
    a: modulesA
  }
}
Copy after login

This is the most basic and complete vuex code; vuex contains five A basic object:

  1. #state: stores state. That is, variables;

  2. #getters: derived status. That is, get in set and get has two optional parameters: state and getters, which can respectively obtain variables in state and other getters. External calling method: store.getters.personInfo(). It’s similar to vue’s computed;

  3. mutations: Submit status modifications. That is, set in set and get. This is the only way to modify state in vuex, but it does not support asynchronous operations. The first parameter defaults to state. External calling method: store.commit('SET_AGE', 18). Similar to methods in vue.

  4. actions: similar to mutations. However, actions support asynchronous operations. The first parameter defaults to an object with the same parameter attributes as the store. External calling method: store.dispatch('nameAsyn').

  5. modules: submodule of store, the content is equivalent to an instance of store. The calling method is similar to that introduced before, except that the current submodule name must be added, such as: store.a.getters.xxx().

How to use vuex in vue-cli

Generally speaking, we will use vue-cli for actual development. In vue -cli, the development and calling methods are slightly different.

├── index.html
├── main.js
├── components
└── store
  ├── index.js     # 我们组装模块并导出 store 的地方
  ├── state.js     # 跟级别的 state
  ├── getters.js    # 跟级别的 getter
  ├── mutation-types.js # 根级别的mutations名称(官方推荐mutions方法名使用大写)
  ├── mutations.js   # 根级别的 mutation
  ├── actions.js    # 根级别的 action
  └── modules
    ├── m1.js     # 模块1
    └── m2.js     # 模块2
Copy after login

state.js example:

const state = {
  name: 'weish',
  age: 22
};

export default state;
Copy after login

getters.js example (we generally use getters to get the state of state instead of using state directly):

export const name = (state) => {
  return state.name;
}

export const age = (state) => {
  return state.age
}

export const other = (state) => {
  return `My name is ${state.name}, I am ${state.age}.`;
}
Copy after login

mutation- type.js example (we will put the function names of all mutations in this file):

export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';
Copy after login

mutations.js example:

import * as types from './mutation-type.js';

export default {
  [types.SET_NAME](state, name) {
    state.name = name;
  },
  [types.SET_AGE](state, age) {
    state.age = age;
  }
};
Copy after login

actions.js example (asynchronous operations, multiple commits time):

import * as types from './mutation-type.js';

export default {
  nameAsyn({commit}, {age, name}) {
    commit(types.SET_NAME, name);
    commit(types.SET_AGE, age);
  }
};
Copy after login

modules--m1.js example (if it is not a very complex application, generally speaking it will not be divided into modules):

export default {
  state: {},
  getters: {},
  mutations: {},
  actions: {}
};
Copy after login

index.js example (assembly of vuex ):

import vue from 'vue';
import vuex from 'vuex';
import state from './state.js';
import * as getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';
import m1 from './modules/m1.js';
import m2 from './modules/m2.js';
import createLogger from 'vuex/dist/logger'; // 修改日志

vue.use(vuex);

const debug = process.env.NODE_ENV !== 'production'; // 开发环境中为true,否则为false

export default new vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    m1,
    m2
  },
  plugins: debug ? [createLogger()] : [] // 开发环境下显示vuex的状态修改
});
Copy after login

Finally, just mount the store instance to vue in main.js

import store from './store/index.js';

new Vue({
 el: '#app',
 store,
 render: h => h(App)
});
Copy after login

When used in vue components, we usually use mapGetters, mapActions, mapMutations, and then You can call these variables or functions in the same way that vue calls methods and computed. The example is as follows:

import {mapGetters, mapMutations, mapActions} from 'vuex';

/* 只写组件中的script部分 */
export default {
  computed: {
    ...mapGetters([
      name,
      age
    ])
  },
  methods: {
    ...mapMutations({
      setName: 'SET_NAME',
      setAge: 'SET_AGE'
    }),
    ...mapActions([
      nameAsyn
    ])
  }
};
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed interpretation of performance optimization in JavaScript

##In vue.js, the problem of default routing not loading

How to use js to convert between timestamp and date format

About the responsive principle in Vue (detailed tutorial)

The above is the detailed content of Detailed interpretation of the management mode vuex in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template