import { createApp } from "vue";
import { createPinia } from "pinia";
import "./style.css";
import App from "./App.vue";
import router from "./router";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
const app = createApp(App);
const pinia = createPinia();
app.use(router);
app.use(pinia);
app.use(ElementPlus);
app.mount("#app");
购物车首页
商品列表
购物车
添加到购物车
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { getProducts } from "../api/product";
import { ElMessage } from "element-plus";
import { buyProducts } from "../api/product.js";
const useShoppingCarStore = defineStore("shopping-car", () => {
//初始化商品列表数据
const productList = ref([]);
//初始化购物车列表数据
const shopCarList = ref([]);
//1s中之后返回数组数据
export const getProducts = async ()=>{
//为了模拟真实的接口请求
await wait(1000)
return products
}
const useShoppingCarStore = defineStore("shopping-car", () => {
//初始化两行
......
//初始化商品列表数据的方法(使用async方法,没有一大堆回调函数
const getProductList = async () => {
const res = await getProducts();
productList.value = res;
};
// const getProductList = () => {
// getProducts().then((res) => {
// productList.value = res;
// });
// };
//给购物车添加数据的方法
const addShopCarList = (row) => {
//1. 减去商品列表页面的商品库存
const res = productList.value.find((item) => item.id === row.id);
if (res.number < 1) {
ElMessage.error({
message: "没有库存辣!",
duration: 1000,
});
return;
}
res.number--;
//2. 添加购物车列表页面的商品数量
const _res = shopCarList.value.find((item) => item.id === row.id);
//2.1 判断购物车列表数据中是否包含当前的商品 如果包含 让数量自增
//2.2 如果不包含 将这个商品添加到购物车列表
if (!_res) {
shopCarList.value.push({
id: row.id,
title: row.title,
price: row.price,
number: 1,
});
} else {
_res.number++;
}
//给购物车列表中的商品按照id的升序做一个排序
shopCarList.value.sort((a, b) => {
return a.id - b.id;
});
};
...
return{...addShopCarList,...};
getProductsList方法最好使用async和await语法,而不是等价的.then。因为async和await语法不涉及大量的回调函数,也就不用进行大量的回调函数嵌套,处理起来更简单不容易出错。
//初始化商品列表数据的方法
const getProductList = async () => {
const res = await getProducts();
productList.value = res;
};
// const getProductList = () => {
// getProducts().then((res) => {
// productList.value = res;
// });
// };
const useShoppingCarStore = defineStore("shopping-car", () => {
//初始化商品列表数据
......
//计算shopcarList里的商品总价
const totalPrice = computed(() => {
//reduce
return shopCarList.value.reduce((pre, cur) => {
return pre + cur.number * cur.price;
}, 0);
});
.....
return {...totalPrice,...};
});
const useShoppingCarStore = defineStore("shopping-car", () => {
......
//结算商品列表的方法
const calc = async () => {
const res = await buyProducts();
if (res) {
ElMessage.success({
message: "结算成功",
duration: 1000,
});
shopCarList.value = [];
} else {
ElMessage.error({
message: "结算失败",
duration: 1000,
});
}
};
return {
....
calc,
};
});
商品总价是:{{ shoppingCarStore.totalPrice }}
结算商品