store(state, mapState, etc.) usage in vuex

1. Introduce the four vajras in vuex: State, movements, Actions and Getters

(for the difference between localStorage and this storage, you can search it if you are interested.)

  1. State(state)

    1. Vuex uses a single state tree and contains all application level states with one object. At this point, it exists as a "unique data source (SSOT)". This also means that each application will contain only one store instance. The single state tree allows us to directly locate any specific state fragment, and easily obtain a snapshot of the current application state during debugging. Simple and crude understanding: we need to put the amount of state management here, and then operate it later.

      //Declare a state
      const state = {
        blogTitle: 'bolg title',
        views: 10,
        blogNumber: 100,
       	total: 0,
        todos: [
          {id: 1, done: true, text: 'To do 1'},
          {id: 2, done: false, text: 'To do 2'},
          {id: 3, done: true, text: 'To do 3'},
        ]
      }
      
  2. Mutation

    1. We have a state tree. If we want to change its state (value), we must specify the only method mutation with vue. The official website says that the only way to change the state in Vuex's store is to submit mutation. Mutation in Vuex is very similar to events: each mutation has a string event type and a callback function (handler). Simple and crude understanding: any person who does not change the value of state in the way of mutation is playing a rogue (illegal)

      //Create a mutation
      const mutation = {
        addViews (state) {
          state.views++
        },
        blogAdd (state) {
          state.blogNumber++
        },
        clickTotal (state) {
          state.total++
        }
      }
      
  3. Action

    1. The role of action is consistent with that of mutation. It submits mutation to change the state, which is an enhanced version of changing the state. The official website says: action is similar to mutation, but the difference is: 1 The action submits the mutation instead of directly changing the status. 2.Action can contain any asynchronous operation.

      const actions = {
        addViews ({commit}) {
          commit('addViews')
        },
        clickTotal ({commit}) {
          commit('clickTotal')
        },
        blogAdd ({commit}) {
          commit('blogAdd')
        }
      }
      
  4. Getter

    1. The official website said: sometimes we need to derive some states from the state in the store, such as filtering and counting the list. Reduce our operations on these status data

      Simple and crude understanding: the data on the state tree is more complex, so we should simplify the operation when using it. The above state Todos is an object. When selecting different data in a component, it needs to be processed. In this way, it needs to be processed once every time. We simplify the operation, process it in the getter, and then export a method;

      const getters = {
       	getToDo (state) {
       	return state.todos.filter(item => item.done === true)
       	// The filter iterates through the value of each item Done = = true, pick it out and return an array
       }
      }
      

2. Use

  1. Create a new file store under src js
  2. main.js
  3. Used in components
  4. See the code address at the end for details. git clone can be downloaded immediately

3.mapState, mapGetters, mapActions, mapMutations

An auxiliary function corresponding to the four vajras

  1. mapState

    When a component needs to obtain multiple states, declaring these states as calculation attributes will be somewhat repetitive and redundant. To solve this problem, we can use the mapState helper function to help us generate computational properties, so that you can press the keyboard a few times less. Corresponding official website: https://vuex.vuejs.org/zh-cn/state.html

    #Example code
    #html
    <p>
      mapState mode{{viewsCount}};<br/>
      Direct use views{{this.$store.state.views}}
    </p>
    
    #js
    ...mapState({
    	viewsCount: 'views'
    })
    
    We need to use a tool function to merge multiple objects into one ... Method is appropriate, merge multiple function methods into one object, and vuex Medium this.$store.views Map to this.viewsCount (this -> vue)From the above, it can avoid reuse in multiple states, and when the mapped values and state When the status values are equal, they can be used directly
    ...mapState({
     'views'
     }),
    
  2. mapMutations

    mapMutations is actually similar to mapState in that it maps the methods in the component to store Commit calls the above code:

    <span>{{this.$store.state.total}}</span>
    <p><button @click="totalAlise">Click Add total</button>
      
    ...mapMutations({
      totalAlise: 'clickTotal' // clickTotal is a method in mutation, and totalalign is a redefined alias method. This component calls this method directly
    })
    
  3. mapActions

    An auxiliary function of action, which maps the methods of the component to store Dispatch call

    <h4>blogNumber number</h4>
    <span>state in blogNumber:{{this.$store.sate.blogNumber}}</span>
    
    created(){
     // this.$store.dispatch('blogAdd')
     // Directly trigger the action through the store method and change the value of views
     this.blogAdd() // Trigger mutation through mapActions to commit and change the value of state
    }
    
    ...mapActions({
      blogAdd: 'blogAdd' // blogAdd is a defined function name, which is attached to this(vue) instance. blogAdd is the function method name in actions 
    })
    
  4. mapGetter

    Just map getter s in the store to locally computed properties

    <h5>todos The information inside</h5>
    	<ul>
        <li v-for="item in todosAlise" :key="item.id">
        //< Li V-for = "item in this. $store. State. Todos": key = "item. ID" > here is to directly read the value of the store without filtering. If filtering is needed.
          <span>{{item.text}}</span><br/>
          <span>{{item.done}}</span>
        </li>
    	</ul>
    </h5>
    
    ...mapGetters({
    	todosALise: 'getToDo' // getToDo is not a string. It corresponds to a method name in getter. Then, rename the method name todosALise
    })
    
    //This getToDo is a method defined in getters, which filters out the object attribute done in todos that is true
    getToDo(state) {
      return state.todos.filter(item => item.done === true)
      //The filter iterates through the value of each item Done = = true, pick it out and return an array
    }
    

reference resources:

  1. https://www.php.cn/js-tutorial-394694.html
  2. https://vuex.vuejs.org/zh/guide/state.html# Get - vuex - status in - vue - component
  3. Code address: https://gitee.com/ashscc/vue-ptn

Added by Javizy on Thu, 30 Dec 2021 10:03:28 +0200