Vue basic use of higher-order Vuex

Posted by sunshine66 on Sun, 02 Jan 2022 03:38:14 +0100

I. Introduction

  • Data transmission in Vue components is mainly through parent-child communication, However, when the project reaches a medium and large scale, the communication logic in the component will become very complex. At this time, we can use Vuex to store and process data globally
  • Vuex's accurate official definition is a state management mode. Centralized storage manages the state of all components of the application, which is not only to solve the state dependence of different views, but also to manage and schedule uniformly

Two demo structure

  • Vuex can also be used for modular development

  • Declare to establish a store warehouse as the general entry
//index.js
//Import vuex and declare a store warehouse for state management
import Vue from 'vue'
import Vuex from 'vuex';
import state from './state'
import mutations from './mutations'
import * as getters from './getters'
import * as actions from './actions'

Vue.use(Vuex)
export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
})

III. use

state

  • Used to define data
  • Vue uses only one state singleton for each application. A state book is used to manage the state of all components under the application. The application data defined in state is equivalent to the initialization data of data. The difference is that state is an object type
//state.js
const state = {
    items: []
}
export default state

getter

  • Used to return a value
  • Similar to computed, the return value of getter will also be cached according to its dependency. Only when its dependency value changes will it start to change.
  • Similar in function, it is also called Vuex modifier, which can directly operate and process the data in state. However, it is generally used to return the value in state without directly exposing the value in state
  • The first parameter received is state, and the second is other getters
//getter.js
export const items = function(state){
    return state.items;
}

mutation

  • Modify value
  • The only way to change the data in Vuex is to submit mutation. In use, functions are generally used to modify the data. The parameters of the functions used are proposed to be passed into state. However, it should be noted that the functions in mutation are synchronous functions and asynchronous functions cannot be used.
  • The pushProduct() function in the demo adds goods to the shopping cart, and addNum() increases the number of goods in the shopping cart
const mutations = {
    pushProduct(state, product) {
        state.items.push({
            id: product.id,
            title: product.title,
            quantity: 1
        })
    },

    addNum(state, product) {
        const cartItem = state.items.find(item => item.id === product.id);
        cartItem.quantity++;
    }
}

export default mutations

Action

  • Action is very similar to mutation. An action submits a mutation instead of directly changing the status data. An action can also contain asynchronous operations. Usually, the upper level function is used in the action to trigger the function in the mutation
  • Only one method is directly exposed in the demo, which is added to the shopping cart, and then the function in changes is executed according to whether the commodity already exists in the shopping cart
export const addProduct = function({commit,state},product){
    const cartItem = state.items.find(item => item.id === product.id);
    if(!cartItem){
        commit('pushProduct',{id:product.id,title:product.title});
    }else{
        commit('addNum',cartItem);
    }
}

Four demo implementation

  • App.vue
<template>

  <div>
    <ul>
      <li v-for="item in listData" :key="item.id">
        <h3>{{ item.title }}</h3>
        <button @click='addProduct(item)'>Add to cart</button>
      </li>
    </ul>
    <hr>
    <h1>Shopping Cart</h1>
    <ul>
      <li v-for="item in items" :key="item.id">
        <h1>{{item}}</h1>
      </li>
    </ul>
  </div>
</template>

<script>
import { mapGetters,mapActions } from "vuex";
export default {
  computed: {
    ...mapGetters(["items"]),
  },
  methods:{
    ...mapActions([
      'addProduct'
    ])
  },
  data() {
    return {
      listData: [
        {
          id: 1,
          title: "snacks",
        },
        {
          id: 2,
          title: "Fruits",
        },
        {
          id: 3,
          title: "Drinks",
        },
        {
          id: 4,
          title: "fresh ",
        },
      ],
    };
  },
};
</script>

  • Function realization:

Five map auxiliary functions

  • Take actions or changes as an example. If you do not use the map function, when there are more functions stored in actions or changes, you can use it in app The introduction of the main interface of Vue will be cumbersome and bloated
computed:{
    userInfo(){
      return this.$store.state.userInfo
    },
    
   	token(){
      return this.$store.state.token
    },
    
     friends(){
      return this.$store.state.friends
    },
    
    likes(){
     return this.$store.state.likes
    },
    ...
  }

Here, we can introduce the map auxiliary function. This method can also automatically map the required state value to the calculation attribute of the instance. The declared method name is assumed to be the passed in method name by default

import { mapActions } from "vuex";

 computed: mapActions(['likes','friends','token','userInfo'])

However, if we want to customize the declared method name instead of the same as the passed in method name, we can use the ternary operator to realize automatic matching

import { mapActions } from "vuex";
 computed: ...mapActions(['mylikes','myfriends','mytoken','myuserInfo'])

Reference link: vuex

Topics: Vue