0
点赞
收藏
分享

微信扫一扫

29,vuex的更改 和当前用户购物车数据

紫荆峰 2022-03-22 阅读 17
前端

store文件下

mutations-types.js

export const USER_LOGIN = "userLogin";
export const INIT_USER = "initUser";
export const Login_OUT = "loginOut";

改成小写

app.vue

export default {
  created() {
    this.$store.commit("initUser");
  },
};

 

 

刷新 一样使用

加入购物车

 新建个表

 后端  index.js  addCart接口

测试

 // 查询用户
  connection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      console.log(results[0]);
    
    }
  );

 

 接口

//添加购物车数据
router.post("/api/addCart", function (req, res, next) {
  //后端接收前端的参数
  let goodsId = req.body.goodsId;
  // //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);

  // console.log(tel);
  // res.send({
  //   data: { a: 1 },
  // });
  // 如果执行,就证明token过期了
  // if (getTimeToken(tokenObj.exp)) {
  //   res.send({
  //     data: {
  //       code: 1000,
  //     },
  //   });
  // }

  // 查询用户
  connection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      console.log(results[0]);
      // 用户id
      let uId = results[0].id;
      // 查询商品;
      connection.query(
        `select * from goods_list where id=${goodsId}`,
        function (err, result) {
          let goodsName = result[0].name;
          let goodsPrice = result[0].price;
          let goodsImgUrl = result[0].imgUrl;
          //查询当前用户在之前是否添加过本商品
          connection.query(
            `select * from goods_cart where uId=${uId} and goods_id=${goodsId}`,
            function (e, r) {
              //用户之前是添加过商品到购物车
              if (r.length > 0) {
                let num = r[0].goods_num;
                connection.query(
                  `update goods_cart set goods_num = replace(goods_num,${num},${
                    parseInt(num) + 1
                  }) where id = ${r[0].id}`,
                  function (e, datas) {
                    res.send({
                      data: {
                        code: 200,
                        success: true,
                        msg: "添加成功",
                      },
                    });
                  }
                );
              } else {
                //没有
                connection.query(
                  `insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`,
                  function () {
                    res.send({
                      data: {
                        code: 200,
                        success: true,
                        msg: "添加成功",
                      },
                    });
                  }
                );
              }
            }
          );
        }
      );
    }
  );
});

 ue

 

 //加入购物车
    addCart() {
      let id = this.$route.query.id;
      http
        .$axios({
          url: "/api/addCart",
          method: "post",
          data: {
            goodsId: id,
          },
          headers: {
            token: true,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.success) {
            Toast("添加购物车成功");
          }
        });
    },

 购物车数据要使用vuext管理

新建cart.js

cart.vue页面中打开页面就要请求查询后端数据到页面中

created() {
    this.getData();
  },
  methods: {
    async getData() {
      let res = await http.$axios({
        url: "/api/selectCart",
        method: "post",
        headers: {
          token: true,
        },
      });
      console.log(res);
    },

发送token  代表查询当前用户

 后台接口

//查询购物车数据
router.post("/api/selectCart", function (req, res, next) {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //查询用户
  connection.query(
    `select * from user where tel = ${tokenObj.tel}`,
    function (error, results) {
      //用户id
      let uId = results[0].id;
      //查询购物车
      connection.query(
        `select * from goods_cart where uId = ${uId}`,
        function (err, result) {
          res.send({
            data: {
              code: 200,
              success: true,
              data: result,
            },
          });
        }
      );
    }
  );
});

 点击购物车

 得到数据

mutations-types.js

export const CART_LIST = "cardList";

cart.js

 

import { CART_LIST } from "./mutations-types";
export default {
  state: {
    list: [],
  },
  getters: {},
  mutations: {
    [CART_LIST](state, cartArr) {
      state.list = cartArr;
    },
  },
  actions: {},
};

cart.vue

 

import { mapState, mapMutations, } from "vuex";
export default {
  name: "Cart",
  data() {
    return {
      checked: true,
      value: 222,
    };
  },
  computed: {
    ...mapState({
      list: (state) => state.cart.list,
    }),
  },
  created() {
    this.getData();
  },
  methods: {
    ...mapMutations(["cardList"]),
    async getData() {
      let res = await http.$axios({
        url: "/api/selectCart",
        method: "post",
        headers: {
          token: true,
        },
      });
      this.cardList(res.data);
      console.log(res);
    },

 引入vuex   并把值给cartList   

循环list

 渲染数据到页面

  <ul>
        <li v-for="(item, index) in list" :key="index">
          <div class="check">
            <van-checkbox v-model="checked"></van-checkbox>
          </div>
          <h2><img :src="item.goods_imgUrl" alt="" /></h2>

          <div class="goods">
            <div class="goods-title">
              <span>{{ item.goods_name }}</span>
              <i class="iconfont icon-fanhui"></i>
            </div>
            <div class="goods-price">$ {{ item.goods_price }}</div>
            <van-stepper v-model="item.goods_num" />
          </div>
        </li>
      </ul>

 

 

 

有点丑  哈哈。。有空再改吧 

举报

相关推荐

0 条评论