vuex

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 way. The biggest characteristic is responsive.

What state needs to be shared across multiple components?

  • State that needs to be shared across multiple interfaces in large projects
  • For example, the user login status, user name, profile picture, and geographical location
  • Such as a collection of goods, items in a shopping cart, etc

Vuex can be used as props, but if there is no direct correlation between two components, then vuex needs to be introduced

/ / 1 installation
npm install vuex --save

// create a/SCR /store folder and create an index.js file.
import Vuex from 'vuex'
/ / 2.2 installation
Vue.use(Vuex);
// 2.3 Creating objects
const store = new Vuex.Store({ })
// 2.4 Export storer objects
export default store

// 3 go back to main.js
import store from './store'
Copy the code

Simple to use

// In the vuex object, create a new state property to store public data
const store = new Vuex.Store({
	state: {
		xmsg: 'a share msg.'}})Copy the code
// In the component template<h1>{{$store.state.xmsg}}</h1>
Copy the code
// You can use this method to bind events, but it is not recommended<button @click='$store.state.xmsg'>button</button>
Copy the code

Because it can be difficult to track which page is being manipulated when tied to a single page, the following is recommended, using a process called Actions >Mutations >State. Mutations helps you record the page object of the operation (which can be viewed in Vue Devtools) in order to facilitate debugging.

You can skip Actions directly, using the Mutations->State process, but this is only for synchronous operations, and cannot be skipped if there is an asynchronous operation.

Therefore, Actions are mainly used for asynchronous operations, that is, receiving back-end data (Backend API) when sending network requests.

state

Store common state/shared data

Vue proposed the concept of a Single Source of Truth, that is, it is recommended that your state information be stored in a Single Store object. If you create multiple Store objects, it will be extremely difficult to manage and maintain them later. Therefore, Vuex uses a single state tree to manage all states at the application level. It can find fragments of a state in the most direct way and facilitate management and maintenance during maintenance and debugging.

The only way to change the state in a store is to commit mutation explicitly.

getters

Similar to computing properties, storing common computing properties and also used for filtering and parameter passing

If we already have a getters that gets a list of all students over the age of 20, the code could be written like this

getters:{
	greaterAgesstus: state= > {
		return state.students.filter(s= > s.age >= 20)},greaterAgescount: (state, getters) = > {
		return getters.greaterAgesstus.length
}
}
Copy the code

Getters cannot pass arguments by default; if you want to pass arguments, you have to make getters return another function.

In the example above, we want to get information about the user based on their ID

getters:{
	stuByID: state= > {
 return id= > {
   return state.students.find(s= > s.id === id)
 }
}
}
Copy the code

mutations

Status updates, a function for holding common operations

  • == The only way to update the store status of Vuex is to submit Mutation==
  • Mutation mainly consists of two parts: The event type of the string and a callback function (handler). This callback function automatically passes a state parameter as the first parameter and a payload as the second parameter. Payload can also be an object
// counter case<h1>{{$store.state.count}}</h1>
<button @click='add'>+</button>
<button @click='sub'>-</button>
<button @click='addNum(10)'>+ 10</button>
Copy the code
methods:{
  add(){ this.$store.commit('increment')},sub(){ this.$store.commit('decrement')},addNum(num){ this.$store.commit('incrementNum', num) },
 
  // Special commit encapsulation (payload passed in multiple object parameters)
  addNum(num){ 
    this.$store.commit({
      type: 'incrementNum2', 
      num
    }),
  }
}
// Do this indirectly via vuex's commit method
Copy the code
const store = new Vuex.Store({
	state: {
		count: 0
	},
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    },
 		incrementNum(state, num) {
      state.count += count
    },
    incrementNum2(state, payload) {
      state.count += payload.count
    }
  }
})
Copy the code

Mutations D Principles of response: 1. The desired attributes must be initialized in the Store ahead of time; 2. Use the set() and delete() methods to perform reactive operations

mutations: {
	updateInfo(state) {
    // You can't use this method to implement responsiveness
    state.info['address'] = 'beijing';
    delete state.info.msg;
    
    // Only the following methods can be used
    Vue.set(state.info, 'address'.'beijing');
    Vue.delete(state.info, 'msg'); }}Copy the code

In general, Vuex requires that the methods defined in Mutation be synchronous. The main reason is that devTools can help us capture a snapshot of Mutation when we use DevTools. But if the operation is asynchronous, DevTools will not do a good job of tracking when the operation is completed.

To implement asynchronous operations, you must use Actions

Mutations method in VUex, to call another method in mutations, again use COMMIT, just use this.com MIT (‘function’), and the current this refers to mutations in the current module;

Pass multiple parameters:

In this case, the parameter cannot be added to the end, because the following parameter is invalid and the passed parameter is undefined.

The official website explains: In most cases, the payload should be an object so that it can contain multiple fields, And the recorded mutation will also be more descriptive;

So, we can pass in parameters as objects, and multiple properties are multiple parameters.

Blog.csdn.net/weixin_3056…

actions

One of the arguments passed in by default is context

mutations: {
  updateInfo(state) {
    state.info.msg = 'hello';
}
actions: {
	aUpdateInfo(context) {
    // Simulate asynchronous operations
    setTimeout(() = > {
      // State can only be implemented on mutations
      // context.state.info.msg = 'hello' 
      context.commit(updateInfo)
    }, 1000)}}Copy the code
metheds: {
  updateInfo() {
    this.$store.dispatch('aUpdateInfo')}}Copy the code

modules

Module means Module. Why do we use modules in Vuex

Vue uses a single state tree, which means that a lot of state is handed over to Vuex to manage. When the application becomes very complex, the Store object can become quite bloated. To solve this problem, Vuex allows us to split the Store into modules, and each Module has its own state, mutations, actions, getters, and so on

const moduleA = {
  state: () = >({... }),mutations: {... },actions: {... },getters: {... }}const moduleB = {
  state: () = >({... }),mutations: {... },actions: {... }}const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA status
store.state.b // -> moduleB status
Copy the code

Store directory structure

/ Store ├── index.js # We build up the module and export the store to place ├─ actions. Js # root level action ├── mutations. Js # mutation ├─ getters ├─ ├─ modulesb.txt # ├─ modulesb.txt #Copy the code
import Vue from 'vue'
import Vuex from 'vuex'

import mutations from './mutations
import actions from './actions
import getters from './getters
import moduleA from './modules/modulesA
import moduleB from './modules/modulesB Vue.use(Vuex); const state = { ... } const store = new vuex. store ({state, mutations, actions, getters, modules: {a: moduleA, b: moduleB } }) export default storeCopy the code
// simulation.js actions.js getters.js is stored as a separate file
export default{... }Copy the code