preface

To get a better impression of Vuex and understand the various method calls of Vuex, I wrote an example to try it out

The final result

The following code

shop.vue
<! -- * @Author: hhyt * @Date: 2021-06-25 11:20:53
 * @LastEditTime: 2021-05-27 10:10:02
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vuedemo/src/web/shop.vue --> <! -- --> <template> <div> <ul> <li class="itemLi" v-for="(item, index) in goods" :key="item + index"> <img class="itemLeft" src="https://pic3.zhimg.com/80/v2-8f173ae25ccc3a0cd93fd1e2bbbecaae_1440w.jpg" alt="" /> <div style="margin-left:30px"> <span>{{ item.name }}</span> <span>{{ item.index }}</span> <p> <span>{{ item.price }}</span> </p> <p> <span class="bor" @click="reduceGoods(index)">-</span> <span class="bor">{{ item.num }}</span> <span class="bor" @click="addGoods(index)">+</span> <span class="bor" @click="useAdd({index: index, num: 10})" > --> <! - < span class = "bor @ click" = "cs (index, num)" > a add 10 < / span > -- > < / p > < / div > < / li > < / ul > < div class = "" > < p > the current total number of commodity: {{totalNum}}</p> <p> {{ totalPrice }}</p> </div> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from "vuex"; export default { data() { return {}; }, computed: { ... mapState(["totalPrice", "totalNum", "goods"]), ... mapGetters(["getTotalNum", "getTotalPrice"]), }, methods: { ... mapMutations(["addGoods", "reduceGoods"]), ... MapActions (["useAdd"]), // Note: // this.$store. Dispatch ("useAdd", {index: $store. index, num: num }); / /}}}; </script> <style scoped> .itemLi { display: flex; justify-content: flex-start; } .itemLeft { width: 80px; height: 80px; } .bor { display: inline-block; padding: 5px 10px; border: 1px solid #ccc; text-align: center; cursor: pointer; } </style>Copy the code
New/store/index. Js
/* * @Author: hhyt * @Date: 2021-05-24 17:45:53 * @LastEditTime: 2021-05-27 10:29:09 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: /vuedemo/src/store/index.js */
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    totalPrice: 0.totalNum: 0.goods: [{id: 1.name: "vue".price: 10.num: 0}, {id: 2.name: "react".price: 20.num: 0}, {id: 3.name: "angular".price: 30.num: 0,}]},getters: {
    // Get the total number of carts
    getTotalNum(state) {
      let newNums = 0;
      state.goods.forEach((item) = > {
        newNums += item.num;
      });
      return newNums;
    },
    // Get the total cart price
    getTotalPrice(state) {
      let newPrice = 0;
      state.goods.forEach((item) = > {
        newPrice += item.num * item.price;
      });
      returnnewPrice; }},mutations: {
    // Initialize the total price and quantity
    initState(state) {
      state.totalPrice = this.getters.getTotalPrice;
      state.totalNum = this.getters.getTotalNum;
    },
    // Add the number of products
    addGoods(state, index) {
      state.goods[index].num++;
      this.commit("initState");
    },
    // Reduce the quantity
    reduceGoods(state, index) {
      state.goods[index].num--;
      this.commit("initState");
    },
    // Add 10 at a time
    addGoodsTen(state, obj) {
      console.log(obj);
      state.goods[obj.index].num += obj.num;
      this.commit("initState");
    },
    // Note !!!!! If you want to change the source object, the copy will still change the original object, so use deep clone to copy the object and then assign the value
    // saveUserInfo(state, info) {
    // Create a new object and copy the info,state.personInfo object into the new object
    //let data = Object.assign({}, state.personInfo, info);
    // Point state.personinfo to the reference address of the new object
    //state.personInfo = data;
    // },
  },
  actions: {
    // The action commits mutation instead of a direct state change. Mutation can change the state directly.
    // Action can contain any asynchronous operation. Mutation can only be a synchronous operation.
    // The action is submitted with this.$store.dispatch('ACTION_NAME',data). Mutation is committed using this. codestore.mit ('SET_NUMBER',10).
    useAdd({ commit }, obj) {
      commit("addGoodsTen", obj); ,}}});Copy the code

Reference link: juejin.cn/post/684490…