Vuex使用案例(加深印象)

前言

为加深对Vuex的印象,以及对vuex各种方法调用的理解,写了个例子去实际体验了一把

最终效果

QQ20210527-102431-HD.gif

代码如下

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 })"
              >一次添加10个</span
            >
            <!-- 不用辅助函数时候 -->
            <!-- <span class="bor" @click="cs(index,num)"
              >一次添加10个</span
            > -->
          </p>
        </div>
      </li>
    </ul>
    <div class="">
      <p>当前商品总数量:{{ 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"]),
    //注意:传入多个参数不能继续在后面加,加则报错无效,必须第二个参数写成对象形式,在对象中接受多个参数,
    // cs(index, num) {
    //   this.$store.dispatch("useAdd", { index: 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>

新建/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: {
    //获取购物车总数
    getTotalNum(state) {
      let newNums = 0;
      state.goods.forEach((item) => {
        newNums += item.num;
      });
      return newNums;
    },
    //获取购物车总共价格
    getTotalPrice(state) {
      let newPrice = 0;
      state.goods.forEach((item) => {
        newPrice += item.num * item.price;
      });
      return newPrice;
    },
  },
  mutations: {
    //初始化总价和数量
    initState(state) {
      state.totalPrice = this.getters.getTotalPrice;
      state.totalNum = this.getters.getTotalNum;
    },
    //添加产品数量
    addGoods(state, index) {
      state.goods[index].num++;
      this.commit("initState");
    },
    //减少数量
    reduceGoods(state, index) {
      state.goods[index].num--;
      this.commit("initState");
    },
    //一次性添加10个
    addGoodsTen(state, obj) {
      console.log(obj);
      state.goods[obj.index].num += obj.num;
      this.commit("initState");
    },
    //注意!!!!!:如果是想更改源对象,复制后还会改变原对象,所以先用深度克隆复制对象再赋值
    // saveUserInfo(state, info) {
    // 创建一个新的对象,将info,state.personInfo对象复制到新对象中
    //let data = Object.assign({}, state.personInfo, info);
    // 将state.personInfo指向新对象的引用地址
    //state.personInfo = data;
    // },
  },
  actions: {
    // action 提交的是 mutation,而不是直接变更状态。mutation可以直接变更状态。
    // action 可以包含任意异步操作。mutation只能是同步操作。
    // 提交方式不同,action 是用this.$store.dispatch('ACTION_NAME',data)来提交。mutation是用this.$store.commit('SET_NUMBER',10)来提交。
    useAdd({ commit }, obj) {
      commit("addGoodsTen", obj);
    },
  },
});


引用链接:https://juejin.cn/post/6844903558496665607

posted @ 2021-08-25 18:05  瀚海云涛  阅读(184)  评论(0编辑  收藏  举报