Vuex knows how to use

Vuex

Official website

install

Introduce

1. What is Vuex?

Vuex is a state management model developed for Vue.js applications. It adopts centralized storage to manage the state of all components, and ensures that the state changes in a predictable way with corresponding rules.

In short, it is used to maintain data between components

What is state management mode

It includes the following parts
  • state, the data source driving the application;
  • View, map state to view in a declarative way;
  • actions, in response to changes in state caused by user input on the view.

According to the official website summary: It is to extract the shared state of components and manage them in a global single instance mode, no matter where they are, Any component can get state or trigger behavior!

The benefit is to maintain the independence between views and states by defining and isolating various concepts in state management and by enforcing rules, Our code will become more structured and maintainable

1.1 under what circumstances do we use Vuex?

Take chestnut for example: different components need user information and some other public data. Each component sends a request to waste, and does not request the parameters between components to pass from side to side, which is troublesome and error prone. Vuex will help you solve this problem.

Vuex is prepared for the development of large-scale single page applications (SPA). If you need to build a large-scale single page application, you need to consider how to manage the state outside the component. Vuex is the best choice.

Summary: Vuex can help us manage shared state with more concepts and frameworks.

2. Composition of vuex

  • vue scaffold auto create content

    export default new Vuex.Store({
      state: {
      //The status of the vuex, that is, the data. (direct modification is not allowed, only for reading)    
      },
      mutations: {
      //Modify, used to modify data.    
      },
      actions: {
      //action, used to operate rotations, run send ajax    
      },
      modules: {
      }
    })
    

2.1,State

Vuex uses a single state tree - one object for all application level states. It exists as the only data source. Each application will contain only one store instance.

A single state tree allows us to directly locate any particular state fragment.

Personal understanding: equivalent to data attribute in vue

Use

    1. How to declare variables to store data
    1. How to use the data of vuex in other components
    1. How to declare variables to store data
    • Declare variables in the state area of the store/index.js file
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {    //Status, used to store data, similar to data area
        count: 0 
      },
      mutations: {
      },
      actions: {
      },
      modules: {
      }
    })
    
    1. How to use the data of vuex in other components
    • this.$store indicates operation vuex
    • this.$store.state indicates the state area of the operation vuex
    <script>
    export default {
      created() {
        //Get data in vuex
        console.info( this.$store.state.count )
      },
    }
    </script>
    

2.2,Mutation

The only way to change the state in Vuex's store is to commit the mutation. Mutations in Vuex are very similar to events: each of them has an event type of string and a callback function (handler).

This callback function is where we actually make the state change, receiving state as the first parameter.

Use

    1. How to define functions in mutaions and modify the value of state
    1. How to execute functions defined by rotations in other components
    1. How to define functions in transitions and modify the value of state
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {    //Status, used to store data, similar to data area
        count: 0 
      },
      mutations: {
        //Declare the updateCount function and modify the value of count
        updateCount(state, value) {
          state.count = value
        }
      },
      actions: {
      },
      modules: {
      }
    })
    
    1. How to execute functions defined by mutaions in other components
    • this.$store operates on vuex

    • this.$store.commit() triggers the mutations definition function

      this.$store.commit("function name", passed value)

    <script>
    export default {
      created() {
        //Get data in vuex
        console.info( this.$store.state.count )
    
        //Modify the data in vuex by means of mutations
        this.$store.commit('updateCount', 100)
    
      },
    }
    </script>
    

2.3,Action

Action is similar to mutation, with the following differences:

  • Action submits a mutation, not a direct change of state.
  • An Action can contain any asynchronous Action.

Use

    1. How to define functions in actions
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {    //Status, used to store data, similar to data area
        count: 0 
      },
      mutations: {
        //Declare the updateCount function and modify the value of count
        updateCount(state, value) {
          state.count = value
        }
      },
      actions: {
         increment (context) {
          context.commit('increment')
        },
       //Perform asynchronous operation
        incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      },
      //async/await
       async actionA ({ commit }) {
        commit('gotData', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // Wait for actionA to complete
        commit('gotOtherData', await getOtherData())
      }    
    }
      modules: {
      }
    })
    
    1. How to execute functions defined by actions in other components
    • Use this.$store.dispatch('xxx ') to distribute action s in components
    • Use mapActions helper function to map methods of components to store.dispatch
    import { mapActions } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapActions([
          'increment', // Map 'this.increment()' to 'this.$store.dispatch('increment')`
    
          // `mapActions' also supports loads:
          'incrementBy' // Map 'this.incrementBy(amount)' to 'this.$store.dispatch('incrementBy', amount)`
        ]),
        ...mapActions({
          add: 'increment' // Map 'this.add()' to 'this.$store.dispatch('increment')`
        })
      }
    }
    

3. Practical operation

Display the data of state in vuex, and click "change" to change through mutaions of vuex

    1. store/index.js

    1. The home page displays the count value and defines the method to trigger the modification

4. Simplified use of vuex

  • Vuex provides mapState and mapMutaions to simplify the operation of vuex

4.1 mapState auxiliary function

When a component needs to obtain multiple states, it will be redundant to declare these states as calculation properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties

Object expansion operator

The mapState function returns an object. How to use it with computed? Yes. Object expansion operator , we can greatly simplify the writing method:

import { mapState } from 'vuex'

4.2 maplocations auxiliary function

import { mapMutations } from 'vuex'

Tags: Front-end Vue Fragment Attribute

Posted on Wed, 11 Mar 2020 00:06:01 -0400 by pureDesi