Vue learning record 4

Time:2021-7-22

Vuex

Vuex is a state management pattern developed specifically for Vue. JS applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way

Install vuex

1、npm install vuex --save

2. CreatestoreObject,src/store/index.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)

    const state = {};
    const getters = {};
    const mutations = {};
    const actions = {};

    const store = new Vuex.Store({
        state,
        getters,
        mutations,
        actions,
    });

    export default store;

3. In the entry filesrc/main.jsIntroduce and injectstore

   import Vue from 'vue'
   import store from './store'

   new Vue({
        el:'#app',
        store,
   })
Vuex options

1、state

  • definitionstate
    const state = {
        user:null,
    }
  • Get in componentstateBecause the state storage of vuex is responsive, the easiest way to read the state from the store instance is to return a state in the calculation attribute
export default {
    computed:{
        user:this.$store.state.user,
    }
}

The mapstate helper function helps us generate computed properties

import {mapState} from 'vuex'
export default {
    computed:{
        localComputed(){

        },
         //This is in the form of an array. Of course, you can also use the form of an object
        ...mapState([          
            'user'
        ]),
    }
}

2、getters

Vuex allows us to define “getter” in the store (which can be regarded as the calculation property of the store). Just like calculating a property, the return value of a getter is cached according to its dependency, and is recalculated only when its dependency value changes
The getter method takes the following parameters: state, getters (optional)

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
        return state.todos.filter(todo => todo.done)
    },
    Gettodobyid: (state) = > (ID) = > {// returns a function to pass parameters to getter
        return state.todos.find(todo => todo.id === id)
    },
    doneTodosCount: (state, getters) => {
        return getters.doneTodos.length
    }
  }
})
  • Get in componentgetters
export default {
    computed: {
      doneTodosCount () {
        return this.$store.getters.doneTodosCount
      }
    }
}

Again, it can be usedmapGettersauxiliary function

import mapGetters from 'vuex'
export default {
    computed:{
        localComputed(){

        },
        //This is in the form of an array. Of course, you can also use the form of an object
        ...mapGetters([         
            'doneTodosCount'
        ]),
    }
}

3、mutations

The only way to change the state in vuex’s store is to submit a mutation
An important rule is to remember that mutation must be a synchronous function
When you register mutation on the store, the processing function always takes state as the first parameter (if defined in the module, it is the local state of the module), and payload as the second parameter (optional), which can be a variable or an object

  • definitionmutations
const mutations = {
    increment (state, n) {
        state.count += n
    },
}
  • Submit the mutation in the component

You can use this. $store. Commit (‘xxx ‘) to submit the mutations in the component, or use the mapmutations auxiliary function to map the methods in the component to store. Commit calls (store needs to be injected into the root node)

import { mapMutations } from 'vuex'
export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // map 'this. Increment()' to 'this. $store. Commit ('increment')`

      //'mapmutations' also supports loads:
      'incrementby' // map 'this. Incrementby (amount)' to 'this. $store. Commit ('incrementby', amount)`
    ]),
    ...mapMutations({
      Add: 'increment' // map 'this. Add()' to 'this. $store. Commit ('increment')`
    })
  }
}

4、actions

Action submits a mutation, not a direct change of state
An action can contain any asynchronous operation
Register action on the store. The handler always takes context as the first argument and payload as the second (optional)

The context object contains the following properties:

{
  State, // is equivalent to 'store. State'. If it is in a module, it is a local state
  Rootstate, // is equivalent to 'store. State', only exists in the module
  Commit, // is equivalent to ` store. Commit '`
  Dispatch, // equivalent to ` store. Dispatch`
  Getters, // equivalent to ` store. Getters`
  Rootgetters // equivalent to 'store. Getters', only exists in modules
}
  • definitionactions
const actions = {
    increment({commit},amount){
        commit('increment',amount)
    },
}
  • Distribute within componentsactions
import {mapActions} from 'vuex'
export default {
    methods:{
        ...mapActions([
          'increment', // map 'this. Increment()' to 'this. $store. Dispatch ('increment')`

          //Mapactions also supports payload:
          'incrementby' // map 'this. Incrementby (amount)' to 'this. $store. Dispatch ('incrementby', amount)`
        ]),
        ...mapActions({
          Add: 'increment' // map 'this. Add()' to 'this. $store. Dispatch ('increment')`
        })
    }
}

In addition:
1. The state of the application level should be centralized into a single store object
2. Submitting a mutation is the only way to change state, and the process is synchronous
3. Asynchronous logic should be encapsulated in action
4. If the store file is too large, just divide the action, mutation and getter into separate files

This work adoptsCC agreementReprint must indicate the author and the link of this article

Give each hair a name before it’s all gone~