[Vue] Vuex concept and basic usage

Welcome to learn and communicate!!!
Continuously updating

Vuex

1. Concept

Vuex is a Vue plug-in that implements centralized state (data) management in Vue. It centrally manages (reads / writes) the shared state of multiple components in Vue applications. It is also a way of communication between components, and is suitable for communication between any components.

Usage scenario: when multiple components need to share data

2. Vuex flow chart


Process details:

① In the component (page), the function of dispatch() or mapActions() is distributed to the function of actions for processing.

② The actions function can interact with the background or submit it to changes through commit().

③ Changes can interact directly with devtool and update state directly.

④ If there is a calculation attribute (the get function is written in getters), the status passes through $store. Of getters Getters () or mapGetters() to update the component; On the contrary, $store State() or mapState().

3. Build vuex environment

  1. Create file: Src / store / index js

    //Introduce Vue core library
    import Vue from 'vue'
    //Introduce Vuex
    import Vuex from 'vuex'
    //Apply Vuex plug-ins
    Vue.use(Vuex)
    
    //Prepare the actions object -- respond to the user's actions in the component
    const actions = {}
    //Prepare the changes object -- modify the data in the state
    const mutations = {}
    //Prepare the state object -- save the specific data
    const state = {}
    
    //Create and expose store s
    export default new Vuex.Store({
    	actions,
    	mutations,
    	state
    })
    
  2. In main When creating vm in JS, pass in the store configuration item

    ......
    //Introducing store
    import store from './store'
    ......
    
    //Create vm
    new Vue({
    	el:'#app',
    	render: h => h(App),
    	store
    })
    

4. Basic use

  1. Initialize data, configure actions, configure changes, and operate the file store js

    //Introduce Vue core library
    import Vue from 'vue'
    //Introduce Vuex
    import Vuex from 'vuex'
    //Reference Vuex
    Vue.use(Vuex)
    
    const actions = {
        //Action added in response component
    	jia(context,value){
    		// console. Log ('jia in actions is called ', miniStore,value)
    		context.commit('JIA',value)
    	},
    }
    
    const mutations = {
        //Executive plus
    	JIA(state,value){
    		// console. Log ('JIA in changes is called ', state,value)
    		state.sum += value
    	}
    }
    
    //Initialization data
    const state = {
       sum:0
    }
    
    //Create and expose store s
    export default new Vuex.Store({
    	actions,
    	mutations,
    	state,
    })
    
  2. Read data from vuex in component: $store state. sum

  3. Modify data in vuex in component: $store Dispatch ('method name in action ', data) or $store Commit ('method name in changes', data)

    Note: if there is no network request or other business logic, actions can also be crossed in the component, that is, commit can be written directly without writing dispatch

5. Use of Getters

  1. Concept: when the data in state needs to be processed before use, you can use getters processing.

  2. In the store Add getters configuration in JS

    ......
    
    const getters = {
    	bigSum(state){
    		return state.sum * 10
    	}
    }
    
    //Create and expose store s
    export default new Vuex.Store({
    	......
    	getters
    })
    
  3. Read data from component: $store getters. bigSum

6. Use of four map methods

  1. mapState method: it is used to help us map the data in state into calculated attributes

    computed: {
        //Generate calculation attributes with mapState: sum, school, subject (object writing method)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
             
        //Generate calculation attributes with mapState: sum, school, subject (array writing method)
        ...mapState(['sum','school','subject']),
    },
    
  2. mapGetters method: used to help us map the data in getters into calculated attributes

    computed: {
        //Generate calculation attribute with mapGetters: bigSum (object writing method)
        ...mapGetters({bigSum:'bigSum'}),
    
        //Generate calculation attribute with mapGetters: bigSum (array writing method)
        ...mapGetters(['bigSum'])
    },
    
  3. mapActions method: the method used to help us generate a dialogue with actions, that is, $store Function of dispatch (xxx)

    methods:{
        //Generated by mapActions: incrementadd, incrementWait (object form)
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //Generated by mapActions: incrementadd, incrementWait (array form)
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  4. mapMutations method: a method used to help us generate a conversation with mutations, that is, $store Function of commit (xxx)

    methods:{
        //Generated by mapActions: increment and decrement (object form)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        
        //Generated by mapMutations: JIA, JIAN (object form)
        ...mapMutations(['JIA','JIAN']),
    }
    

Note: when mapActions and mapMutations are used, if parameters need to be passed: pass the parameters when binding events in the template, otherwise the parameters are event objects.

7. Modularity + namespace

  1. Purpose: to better maintain the code and make the classification of multiple data more clear.

  2. Modify store js

    const countAbout = {
      namespaced:true,//Open namespace
      state:{x:1},
      mutations: { ... },
      actions: { ... },
      getters: {
        bigSum(state){
           return state.sum * 10
        }
      }
    }
    
    const personAbout = {
      namespaced:true,//Open namespace
      state:{ ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        countAbout,
        personAbout
      }
    })
    
  3. After the namespace is opened, read the state data from the component:

    //Method 1: read directly by yourself
    this.$store.state.personAbout.list
    //Method 2: read with mapState:
    ...mapState('countAbout',['sum','school','subject']),
    
  4. After the namespace is opened, the getters data is read from the component:

    //Method 1: read directly by yourself
    this.$store.getters['personAbout/firstPersonName']
    //Method 2: read with mapGetters:
    ...mapGetters('countAbout',['bigSum'])
    
  5. After namespace is opened, dispatch is invoked in the component.

    //Method 1: directly dispatch yourself
    this.$store.dispatch('personAbout/addPersonWang',person)
    //Method 2: with mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  6. After namespace is opened, commit is invoked in the component.

    //Method 1: commit yourself directly
    this.$store.commit('personAbout/ADD_PERSON',person)
    //Method 2: with mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    

Keywords: Javascript Front-end Vue Vue.js

Added by daucoin on Fri, 28 Jan 2022 09:41:16 +0200