pinia写购物车功能

本文介绍了如何使用Pinia库在Vue应用中实现购物车功能,包括状态管理、添加商品、全选/单选操作以及从API获取和更新购物车数据的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//cart.js

import { defineStore } from "pinia";

export const userCartStore = defineStore({
  id: "cart",
  state: () => {
    return {
      cartList: [], //购物车数据
      select: [], //商品选中的id
    };
  },
  getters: {
    isChecked() {
      return this.select.length === this.cartList.length;
    },
    // 总价
    total() {
      let total = {
        price: 0,
        number: 0,
      };

      this.cartList.forEach((v) => {
        if (this.select.indexOf(v.id) != -1) {
          total.price += v.num * v.price;
          total.number += this.select.length && v.num;
        }
      });
      return total;
    },
  },
  actions: {
    addCart(list) {
      this.select = [];
      list.forEach((v) => {
        v["check"] = true;
        this.select.push(v.id);
      });
      this.cartList = list;
    },
    // 全选
    all() {
      this.select = this.cartList.map((v) => {
        v["check"] = true;
        return v.id;
      });
    },
    // 全不选
    unAll() {
      this.cartList.forEach((v) => {
        v["check"] = false;
        this.select = [];
      });
    },
    // 单选
    itemChecked(index) {
      // 获取点击商品的id
      let id = this.cartList[index].id;
      // 下标查询该id是否被选中
      let idx = this.select.indexOf(id);

      if (idx > -1) {
        //有
        this.cartList[index].check = false;
        this.select.splice(idx, 1);
      } else {
        // 没有
        this.cartList[index].check = true;
        this.select.push(id);
      }
    },
  },
});

//shopCartView.vue


import { userCartStore } from "@/stores/cart";
import { storeToRefs } from "pinia";
const cartStore = userCartStore()

//解构
let {cartList,isChecked,total} = storeToRefs(cartStore)

// 获取购物车数据,将数据存入pinia中

axios.get('http://localhost:3000/shopCart').then((res)=>{
  console.log(res.data);
  cartStore.addCart(res.data)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值