Vuex

1. The concept

A Vue plug-in that implements centralized state (data) management in Vue, centralized management (read/write) of the shared state of multiple components in Vue application, is also a way of communication between components, and is suitable for communication between any components.

2. When to use it?

When multiple components need to share data

3. Set up a VUEX environment

  1. Create a file: SRC /store/index.js

    // Introduce the Vue core library
    import Vue from 'vue'
    / / introduce Vuex
    import Vuex from 'vuex'
    // Apply the Vuex plugin
    Vue.use(Vuex)
    
    // Prepare actions objects that respond to user actions in the component
    const actions = {}
    // Prepare the mutations object -- modify the data in state
    const mutations = {}
    // Prepare the state object -- save the specific data
    const state = {}
    
    // Create and expose store
    export default new Vuex.Store({
    	actions,
    	mutations,
    	state
    })
    Copy the code
  2. The Store configuration item is passed when the VM is created in main.js

    ./ / into the store
    import store from './store'./ / create the vm
    new Vue({
    	el:'#app'.render: h= > h(App),
    	store
    })
    Copy the code

4. Basic

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

    // Introduce the Vue core library
    import Vue from 'vue'
    / / introduce Vuex
    import Vuex from 'vuex'
    / / reference Vuex
    Vue.use(Vuex)
    
    const actions = {
        // Respond to the action added to the component
    	jia(context,value){
    		// console.log(' Jia called in actions ',miniStore,value)
    		context.commit('JIA',value)
    	},
    }
    
    const mutations = {
        / / implementation
    	JIA(state,value){
    		// console.log(' JIA is called on mutations ',state,value)
    		state.sum += value
    	}
    }
    
    // Initialize the data
    const state = {
       sum:0
    }
    
    // Create and expose store
    export default new Vuex.Store({
    	actions,
    	mutations,
    	state,
    })
    Copy the code
  2. $store.state. Sum = $store.state. Sum = $store.state

  3. Modify vuEX data in component: $store.dispatch(‘ method name in action ‘, data) or $store.mit (‘ method name in mutations ‘, data)

    Note: If there is no network request or other business logic, components can skip actions, i.e. write commit instead of dispatch

5. The use of getters

  1. Concept: When the data in state needs to be processed for reuse, you can use getters processing.

  2. Append the getters configuration to store.js

    .const getters = {
    	bigSum(state){
    		return state.sum * 10}}// Create and expose store
    export default new Vuex.Store({
    	......
    	getters
    })
    Copy the code
  3. $store. Getters. BigSum = $store

6. Use of four MAP methods

  1. MapState method: used to help us map the data in state to computed properties

    computed: {
        // Use mapState to generate calculation attributes: sum, school, subject. mapState({sum:'sum'.school:'school'.subject:'subject'}),
             
        // Use mapState to generate calculation properties: sum, school, subject. mapState(['sum'.'school'.'subject']),},Copy the code
  2. MapGetters method: used to help us map the data in getters to computed properties

    computed: {
        // Generate calculated properties with mapGetters: bigSum. mapGetters({bigSum:'bigSum'}),
    
        // Generate calculated properties with mapGetters: bigSum. mapGetters(['bigSum'])},Copy the code
  3. MapActions method: a method to help us generate a dialogue with actions, i.e. a function containing $store.dispatch(XXX)

    methods:{
        // Generate from mapActions: incrementOdd, incrementWait (object form). mapActions({incrementOdd:'jiaOdd'.incrementWait:'jiaWait'})
    
        // Generate from mapActions: incrementOdd, incrementWait. mapActions(['jiaOdd'.'jiaWait'])}Copy the code
  4. MapMutations method: a method that helps us generate the mutations dialogue, that is, a function containing $store.mit (XXX)

    methods:{
        // Create by mapActions: Increment and Decrement (in object form). mapMutations({increment:'JIA'.decrement:'JIAN'}),
        
        // rely on mapMutations to generate: JIA, JIAN. mapMutations(['JIA'.'JIAN']),}Copy the code

Note: When using mapActions and mapMutations, if the parameters need to be transferred, the parameters need to be passed when the event is bound in the template, otherwise the parameters are event objects.

7. Modularity + namespace

  1. Purpose: To make the code more maintainable and to make the classification of multiple data more explicit.

  2. Modify store. Js

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

    // Method 1: Read directly by yourself
    this.$store.state.personAbout.list
    // Use mapState to read:. mapState('countAbout'['sum'.'school'.'subject']),
    Copy the code
  4. After the namespace is enabled, getters data is read from the component:

    // Method 1: Read directly by yourself
    this.$store.getters['personAbout/firstPersonName']
    // Use mapGetters to read:. mapGetters('countAbout'['bigSum'])
    Copy the code
  5. After the namespace is enabled, Dispatch is called in the component

    // Dispatch directly
    this.$store.dispatch('personAbout/addPersonWang',person)
    // Use mapActions:. mapActions('countAbout', {incrementOdd:'jiaOdd'.incrementWait:'jiaWait'})
    Copy the code
  6. After the namespace is enabled, commit is called in the component

    // Method 1: Commit yourself
    this.$store.commit('personAbout/ADD_PERSON',person)
    // Solution 2: use mapMutations:. mapMutations('countAbout', {increment:'JIA'.decrement:'JIAN'}),
    Copy the code