Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

  • Hi, I’m _Peach. Today I’m here to share some Vuex tips from work and make a summary for myself

1. What is Vuex

  • Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue’s official debugging tool devTools Extension (Opens New Window), providing advanced debugging functions such as zero-configuration time-travel debugging and state snapshot import and export.
  • In general, Vuex is responsible for data transfer and sharing

2. Why Vuex

  • When our application encounters multiple component shared states such as:
  • Multiple views depend on the same state.
  • Actions from different views need to change the same state.

Vuex in this mode, our component tree forms a huge “view” where any component can get state or trigger behavior no matter where it is in the tree! By defining and isolating concepts in state management and by enforcing rules to maintain independence between views and states, our code becomes more structured and maintainable.

3. Install Vuex

  • Here I use the NPM setup
npm install vuex --save
Copy the code

Reference it in the main.js file after installation

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
Copy the code

4. Usage

Create store folder, a new index, js, action, js, mutations. Js file

  1. The index.js file is imported with import, and the retro. js file is mounted to the new vuex.store
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
Vue.use(Vuex)

const state = {
  username:' '.// Login user name
}

export default new Vuex.Store({
  state,
  mutations,
  actions
})
Copy the code
  1. Action. Js file
/* vuex-action */
/ / transport
export default {
  saveUserName(context,username){
    context.commit('saveUserName',username)
  }
}
Copy the code
  1. Mutations. Js file
Vuex-mutations */
/ / read
export default {
  saveUserName(state,username){
    state.username = username
  }
}
Copy the code
  1. Import it in main.js first
import store from './store/index';

new Vue({
  store, // Mount it here
  router,
  render: h= > h(App),
}).$mount('#app')

Copy the code
  1. The Action bystore.dispatchMethod trigger:
this.$store.dispatch('SavaUserName',res.username)
Copy the code
  1. By registering in the root instancestoreOption, the store instance will be injected into all the children of the root component, and the children will passthis.$storeAccess to the
this.$store.state.username
Copy the code
  1. Data latency can be resolved by calculating attributes
computed:{
  username(){
    return this.$store.state.username
  }
}
Copy the code

mapStateAuxiliary function

When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties that will save you from pressing the key:

// In the separately built version, the auxiliary function is vuex.mapstate
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // Arrow functions make code more concise
    count: state= > state.count,

    // Pass the string argument 'count' equal to 'state => state.count'
    countAlias: 'count'.// In order to be able to use 'this' to get local state, you must use regular functions
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}
Copy the code

Object expansion operator

  • mapStateThe function returns an object. How do we mix it with local computed properties? Typically, we need to use a utility function to combine multiple objects into one so that we can pass the final object tocomputedProperties. But since there have beenObject expansion operator (Opens New Window), we can greatly simplify writing:
computed: {
  localComputed () { / *... * / },
  // Use the object expansion operator to blend this object into an external object. mapState({// ...})}Copy the code

conclusion

Commit Mutation in the component

You can use this. codeStore.mit (‘ XXX ‘) to commit mutation in the component, or use the mapMutations helper function to map methods in the component to a store.mit call (requiring store injection at the root node).

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment'.// Map 'this.increment()' to 'this.store.com MIT ('increment')'

      // 'mapMutations' also supports payloads:
      'incrementBy' // Map 'this.incrementBy(amount)' to 'this. codestore.com MIT ('incrementBy', amount)'
    ]),
    ...mapMutations({
      add: 'increment' // Map 'this.add()' to 'this.store.mit ('increment')'}}})Copy the code

Distribute the Action in the component

You use this.$store.dispatch(‘ XXX ‘) to distribute actions in the component, or use the mapActions helper function to map the component’s methods to a store.dispatch call (which requires injecting store at the root node first) :

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment'.// Map 'this.increment()' to 'this.$store.dispatch('increment')'

      // 'mapActions' also supports payloads:
      'incrementBy' // Map 'this.incrementBy(amount)' to 'this.$store.dispatch('incrementBy', amount)'
    ]),
    ...mapActions({
      add: 'increment' // Map 'this.add()' to 'this.$store.dispatch('increment')'}}})Copy the code

This is only part of the information, please go to the official vuex documentation for full information