Study 18, VueX state management

VueX state management

1. What is VueX

-Vuex is a state management library specially designed for Vue.js

-Vuex uses a centralized method to store the state that needs to be shared

-Vuex's role is to perform state management, solve complex component communication, and data sharing

-Vuex is integrated into devtools, providing time-travel time travel history rollback function

  import Vue from' vue
  import Vuex from' vuex
  Vue.use (Vuex)
  export default new Vuex.Store({
      state: {},
      getters: {},
      mutations: {},
      actions: {},
      modules: {},
  })

  computed: {
    ...mapState({ num: 'count',message: 'msg' }),
    ...mapGetters([ reverseMsg' ] )
  },
  methods: {
    ...mapMutations([ 'increate' ]),
    ...mapActions([ 'increateAsync' ])
  },

  Use $store.commit to trigger the mutation,

  Use $store.dispatch to trigger the action,

 

Second, when to use VueX

-Don't use Vuex unless necessary

-Large single page application

  -Multiple views depend on the same state

  -Actions from different views need to change the same state

 

Three, VueX plug-in introduction

-VueX plugin is just a function

-This function accepts a store parameter

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    products,
    cart
  },
  plugins: [myPlugin]
})

const myPlugin = store => {
  store.subscribe((mutation, state) => {
    if (mutation.type.startsWith('cart/')) {
      window.localStorage.setItem('cart-products', JSON.stringify(state.cart.cartProducts))
    }
  })
}

 

Guess you like

Origin blog.csdn.net/qq_40289624/article/details/110002244