Vuex is good for projects that are large or involve data being passed back and forth between multiple components


Install vuex

  • Vue Scaffolding installation VUEX (recommended)
    • Select the vuEX option during creation
  • Install the VUex manually
    npm install --save vuex
    // create a store folder at the same level as main.js, and create index.js inside the folder
    //main.js internally configures vuex
      import store from './store'
      new Vue({
          el: '#app',
          store, / / a mount
          template: '<App></App>'.components: { App }
      });
    Copy the code

Using vuex

  • Creating a folder

z i909

  • index.js The default is to export this file
import Vue from 'vue'
import Vuex from 'vuex'
// Import js files for other modules
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex);
/ / a mount
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
    //modules can subdivide data, suitable for the case of multiple modules
    modules: {}})Copy the code
  • state.js Similar to data, an object is exported by default
export default {
  page: 1 // Here is the managed data
}
Copy the code
  • mutations.js Write method changes data (synchronous operation)
import * as types from './mutations-type' // Import the js file that manages the method name
export default {
  [types.ADD_NUM](state,num) {
    console.log(num,'mutation')
    state.page  = num
  }
}
// Commit in the component
import * as types from './mutations-type'
// The difference between commit and dispatch is that COMMIT is the synchronous operation to submit mutcriticized, while Dispatch is the asynchronous operation to distribute Actions
this.$store.commit(types.ADD_NUM,num);
// Commit in a normal js file
import store from '@/store'
store.commit('Method name'.'value')
// Auxiliary function submission (separate introduction)
Copy the code
  • Actions Write method changes data (asynchronous operation)
export default {
  / / sample
  async reqUserInfo({commit}){
     // Verify from the server side
     let result = await getUserInfo();
     if(200 === result.success_code){
        commit(USER_INFO, {userInfo: result.data}); }}}// call from the component
import * as types from './mutations-type'
// The difference between commit and dispatch is that COMMIT is the synchronous operation to submit mutcriticized, while Dispatch is the asynchronous operation to distribute Actions
this.$store.dispatch(types.USER_INFO,res.data.data);
// call from a normal js file
import store from '@/store'
store.dispatch('Method name'.'value')// Dispatch is an asynchronous operation that distributes actions
// Auxiliary function calls (separate introduction)
Copy the code
  • Getters is similar to calculating properties
export default {
/ / sample
  getUAKey: (state) = > (key) = > { // Get the current environment (applets, wechat,APP)
    return state.userAgent[key]
  },
}
// call from the component
this.$store.getters.getUAKey("wx")
// call in the js file
import store from '@/store'
const miniEnv = store.getters.getUAKey('miniProgram')
Copy the code
  • Retro-types.js definition of submission method (exact derivation)
export const ADD_GOODS = 'ADD_GOODS'; // Add items to cart
export const INIT_SHOP_CART = 'INIT_SHOP_CART'; // Initialize the shopping cart
export const USER_INFO = 'USER_INFO'; // User information
Copy the code
  • Helper functions (can be used to simplify fetching or submission)
// 1. Get state data
import {mapState,mapMutations} from 'vuex'
// this.page is accessible
computed: {
   ...mapState(['page'])},2. submit mutations
 methods: {
    ...mapMutations(['ADD_NUM']),
    add() {
      let num = this.page + 1
      this.ADD_NUM(num) //this.ADD_NUM = mutations}}// 3. Asynchronous data distribution actions
 methods: {
    ...mapActions(['reqUserInfo']),}mounted(){
    // Just call it
    this.reqUserInfo();
},
Copy the code
  • Modules Subdivides modules separately
// store directory index.js
import trace from './modules/trace'
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    trace // Mount the trace file}});Copy the code
  • Create a modules folder in the index.js folder to store js files of other modules. Trace. Js can be written in a JS folder or subdivided into a JS folder.