1. What is Vuex

A state management pattern developed specifically for vue.js applications

1.1 What is the Status Management Mode

The status self-management application contains

  • State: drives the application data source
  • View: map state to the view declaratively
  • Actions: Responds to changes in the view state caused by user actions

1.2 vuex process

2. Core concepts

2.1 the State

Data defined to be shared globally

 state: {
    // All task lists
    list: [].inputVal: 'aaa'.Tmpid: 5.viewKey: 'all'
  }
Copy the code

2.2 Mutations

Asynchronous operations cannot be performed in this function

It is used to change data in store. Only store data can be changed by mutation. Data that cannot be directly operated in store can be centrally monitored for all data changes

 mutations: {
    initList(state, list) {
      // state is a fixed argument assigned to the List in the state store
      state.list = list
    }
   }
Copy the code

2.3 the Actions

Data in state cannot be modified directly in the action unless a mutation function is triggered by context.mit ()

actions: {
    getList(context) {
      axios.get('./list.json').then(({ data }) = > {
        // console.log(data);
        // call the mutation method and pass it a list of values
        context.commit('initList', data)
      })
    }
  },
Copy the code

2.4 the Getter

It doesn’t change the data in state, it’s just a wrapper

getters: {
 unDoneNum(state) {
      return state.list.filter(x= > x.done === false).length
    }
   }
Copy the code

Have return values imported on demand

import { mapGetters } from 'vuex'
Copy the code

In computed, add the function name in the getter to the following array

computed: { ... mapGetters(['unDoneNum'])},Copy the code

2.5 Modules

In a single tree, all the states are concentrated, resulting in a very large object.

Split store into modules

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

3. The application of

Simple calculation cases include source code

3.1 the main js

import Vue from 'vue'
import App from './App.vue'
// Import the store exposed in store
import store from './store'

Vue.config.productionTip = false

new Vue({
  // Mount the store to the instance so that every component in the VUE can access the store data
  store,
  render: h= > h(App)
}).$mount('#app')

Copy the code

3.2 app. Vue

<template>
  <div>
    <my-addition></my-addition>
    <p>-------------</p>
    <my-subtraction></my-subtraction>
  </div>
</template>

<script>
import Addition from './components/Addition.vue'
import Subtraction from './components/Subtraction.vue'
export default {
  data() {
    return{}},components: {
    'my-addition': Addition,
    'my-subtraction': Subtraction
  }
}
</script>

<style>
</style>

Copy the code

3.3 store index. Js

// Initialize the vuex
import Vue from 'vue'
import Vuex from 'vuex'

// Register in the project
Vue.use(Vuex)

// Create an instance of vuex.store with new and expose it
export default new Vuex.Store({
  state: {
    // Define globally shared data
    count: 2
  },
  mutations: {
    // Asynchronous operations cannot be performed in this function
    // It is used to change the data in the store. Only the store data can be changed by mutation, and the data cannot be directly operated in the store can be centrally monitored
    add(state) {
      // state represents a global data object
      /* setTimeout(() => { state.count++ }, 2000); * /
      state.count++
    },
    add1(state, step) {
      // step indicates how many parameters are added at a time
      state.count += step
    },
    / / subtraction
    sub(state) {
      state.count--
    },
    sub1(state, step) {
      state.count -= step
    }
  },
  actions: {
    addAsync(context) {
      setTimeout(() = > {
        // Data in state cannot be modified directly in the action unless a mutation function is triggered by context.mit ()
        context.commit('add')},2000);
    },
    // Async with parameter addition
    addNAsync(context, step) {
      setTimeout(() = > {
        context.commit('add1', step)
      }, 2000);
    },

    subAsync(context) {
      setTimeout(() = > {
       context.commit('sub')},2000);
    },
    // Async with parameter addition
    subNAsync(context, step) {
      setTimeout(() = > {
        context.commit('sub1', step)
      }, 2000); }},modules: {},getters: {
    // Does not change the data in state
    show(state) {
      return 'The current latest quantity is [' + state.count + '】'}}})Copy the code

3.4 the add component

<template> <! - in the templatethisCan be omitted --><div>
    <! $store.state.count = $store.state.count = $store.state.count = $store.state.count = $store.state.count
    <! Use the getter method -->
    <h2>{{$store.getters.show}}</h2>
    <h3>{{$store.state.count}}</h3>
    <button @click="addbtn">+ 1</button>
    <button @click="addbtn1">+n</button>
    <button @click="addbtn2">+1 async</button>
    <button @click="addbtn3">+n async</button>

  </div>
</template>

<script>
export default {
  data() {
    return{}},methods: {
    addbtn() {
      // this.$store.state.count++
      // commit calls one of the mutation functions
      this.$store.commit('add')},addbtn1() {
      The first method is the second method in the subtraction
      this.$store.commit('add1'.2)},/ / asynchronous
    addbtn2() {
      // Specifically trigger action
      this.$store.dispatch('addAsync')},// Async with parameter addition
    addbtn3() {
      this.$store.dispatch('addNAsync'.5)}}}</script>

Copy the code

3.5 sub

<template>
  <div>
    <! The second way for a component to access data: -->
    <! -- Part 3, direct use -->
    <h2>{{$store.getters.show}}</h2>
    <h3>The current count value is: {{count}}</h3>
    <button @click="subbtn">- 1</button>
    <button @click="subbtn1">-n</button>

    <button @click="subbtn2">-1 async</button>
    <button @click="subNAsync(5)">-n async</button>

  </div>
</template>

<script>
// Step 1: Import mapState functions from vuEX as needed
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  data() {
    return{}},// The second step is to map the currently needed global data to a computed property of the component by importing the mapState function. Put the data used in the calculation property into an array
  computed: {
    ...mapState(['count']),
    ...mapGetters(['show'])},methods: {
    ...mapMutations(['sub'.'sub1']),
    ...mapActions(['subAsync'.'subNAsync']),
    subbtn() {
      / / call
      this.sub()
    },
    subbtn1() {
      this.sub1(3)},subbtn2() {
      this.subAsync()
    }
  }
}
</script>

Copy the code