基础思想:如果已经添加过相同的商品,就在其数量count上加想买的数量,如果没有添加过,就直接push到购物车列表中
步骤1
import {defineStore} from "pinia";
export const useCartStore = defineStore(
'cart',
()=>{
},
{
persist:true
}
)
export const useCartStore = defineStore(
'cart',
()=>{
const cartList = ref([]);
const addCart = (goods) => {
//判断商品是否在购物车
const findItem = cartList.value.find(item=>goods.skuId === item.skuId);
if(findItem){
findItem.count += goods.count;
}else {
cartList.value.push(goods)
}
}
return{
cartList,
addCart
}
},
{
persist:true
}
)
重构Detail/index.vue
import {useCartStore} from "@/stores/cartStore";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
const cartStore = useCartStore();
//sku组件触发方法
let skuObj = {};
const skuChange = (sku)=>{
// console.log(sku)
skuObj = sku
}
//购买数量
const count = ref(1);
//添加购物车
const addCart = () => {
console.log(skuObj)
if (skuObj.skuId) {
// 规则已经选择 触发action
cartStore.addCart({
id: goods.value.id,
name: goods.value.name,
picture: goods.value.mainPictures[0],
price: goods.value.price,
count: count.value,
skuId: skuObj.skuId,
attrsText: skuObj.specsText,
selected: true
})
console.log(cartStore.cartList);
} else {
// 规格没有选择 提示用户
ElMessage.warning('请选择规格')
}
}
</script>
...
<!-- 数据组件 -->
<el-input-number v-model="count" :min="1" />
<!-- 按钮组件 -->
<div>
<el-button size="large" class="btn" @click="addCart">
加入购物车
</el-button>
</div>
创建Layout/components/HeaderCart
<script setup>
</script>
<template>
<div class="cart">
<a class="curr" href="javascript:;">
<i class="iconfont icon-cart"></i><em>2</em>
</a>
<div class="layer">
<div class="list">
<!--
<div class="item" v-for="i in cartList" :key="i">
<RouterLink to="">
<img :src="i.picture" alt="" />
<div class="center">
<p class="name ellipsis-2">
{{ i.name }}
</p>
<p class="attr ellipsis">{{ i.attrsText }}</p>
</div>
<div class="right">
<p class="price">¥{{ i.price }}</p>
<p class="count">x{{ i.count }}</p>
</div>
</RouterLink>
<i class="iconfont icon-close-new" @click=""></i>
</div>
-->
</div>
<div class="foot">
<div class="total">
<p>共 10 件商品</p>
<p>¥ 100.00 </p>
</div>
<el-button size="large" type="primary" >去购物车结算</el-button>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
.cart {
width: 50px;
position: relative;
z-index: 600;
.curr {
height: 32px;
line-height: 32px;
text-align: center;
position: relative;
display: block;
.icon-cart {
font-size: 22px;
}
em {
font-style: normal;
position: absolute;
right: 0;
top: 0;
padding: 1px 6px;
line-height: 1;
background: $helpColor;
color: #fff;
font-size: 12px;
border-radius: 10px;
font-family: Arial;
}
}
&:hover {
.layer {
opacity: 1;
transform: none;
}
}
.layer {
opacity: 0;
transition: all 0.4s 0.2s;
transform: translateY(-200px) scale(1, 0);
width: 400px;
height: 400px;
position: absolute;
top: 50px;
right: 0;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
background: #fff;
border-radius: 4px;
padding-top: 10px;
&::before {
content: "";
position: absolute;
right: 14px;
top: -10px;
width: 20px;
height: 20px;
background: #fff;
transform: scale(0.6, 1) rotate(45deg);
box-shadow: -3px -3px 5px rgba(0, 0, 0, 0.1);
}
.foot {
position: absolute;
left: 0;
bottom: 0;
height: 70px;
width: 100%;
padding: 10px;
display: flex;
justify-content: space-between;
background: #f8f8f8;
align-items: center;
.total {
padding-left: 10px;
color: #999;
p {
&:last-child {
font-size: 18px;
color: $priceColor;
}
}
}
}
}
.list {
height: 310px;
overflow: auto;
padding: 0 10px;
&::-webkit-scrollbar {
width: 10px;
height: 10px;
}
&::-webkit-scrollbar-track {
background: #f8f8f8;
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: #eee;
border-radius: 10px;
}
&::-webkit-scrollbar-thumb:hover {
background: #ccc;
}
.item {
border-bottom: 1px solid #f5f5f5;
padding: 10px 0;
position: relative;
i {
position: absolute;
bottom: 38px;
right: 0;
opacity: 0;
color: #666;
transition: all 0.5s;
}
&:hover {
i {
opacity: 1;
cursor: pointer;
}
}
a {
display: flex;
align-items: center;
img {
height: 80px;
width: 80px;
}
.center {
padding: 0 10px;
width: 200px;
.name {
font-size: 16px;
}
.attr {
color: #999;
padding-top: 5px;
}
}
.right {
width: 100px;
padding-right: 20px;
text-align: center;
.price {
font-size: 16px;
color: $priceColor;
}
.count {
color: #999;
margin-top: 5px;
font-size: 16px;
}
}
}
}
}
}
</style>
重构LayoutHeader
import HeaderCart from "@/views/Layout/components/HeaderCart.vue";
...
<!-- 头部购物车 -->
<HeaderCart/>
重构HeaderCart.vue
<script setup>
import { useCartStore } from '@/stores/cartStore'
const cartStore = useCartStore()
</script>
<template>
<div class="cart">
<a class="curr" href="javascript:;">
<i class="iconfont icon-cart"></i><em>{{cartStore.cartList.length}}</em>
</a>
<div class="layer">
<div class="list">
<div class="item" v-for="i in cartList" :key="i">
<RouterLink to="">
<img :src="i.picture" alt="" />
<div class="center">
<p class="name ellipsis-2">
{{ i.name }}
</p>
<p class="attr ellipsis">{{ i.attrsText }}</p>
</div>
<div class="right">
<p class="price">¥{{ i.price }}</p>
<p class="count">x{{ i.count }}</p>
</div>
</RouterLink>
<i class="iconfont icon-close-new" @click=""></i>
</div>
</div>
<div class="foot">
<div class="total">
<p>共 10 件商品</p>
<p>¥ 100.00 </p>
</div>
<el-button size="large" type="primary" >去购物车结算</el-button>
</div>
</div>
</div>
</template>
1- 添加删除action函数
const delCart = (skuId) => {
// 思路:
// 1. 找到要删除项的下标值 - splice
// 2. 使用splice删除找到的项,原数组改变
const idx = cartList.value.findIndex((item) => skuId === item.skuId)
cartList.value.splice(idx, 1)
}
...
return{
cartList,
addCart,
delCart
}
2- 组件触发action函数并传递参数
<i class="iconfont icon-close-new" @click="cartStore.delCart(i.skuId)"></i>
重构cartStore.js
// 计算属性
// 1. 总的数量 所有项的count之和
const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
// 2. 总价 所有项的count*price之和
const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
return{
allCount,
allPrice,
cartList,
addCart,
delCart
}
重构HeaderCart.vue
<div class="foot">
<div class="total">
<p>共 {{allCount}} 件商品</p>
<p>¥ {{allPrice.toFixed(2)}} </p>
</div>
<el-button size="large" type="primary" >去购物车结算</el-button>
</div>
创建View/CartList/index.vue
<script setup>
const cartList = []
</script>
<template>
<div class="xtx-cart-page">
<div class="container m-top-20">
<div class="cart">
<table>
<thead>
<tr>
<th width="120">
<el-checkbox/>
</th>
<th width="400">商品信息</th>
<th width="220">单价</th>
<th width="180">数量</th>
<th width="180">小计</th>
<th width="140">操作</th>
</tr>
</thead>
<!-- 商品列表 -->
<tbody>
<tr v-for="i in cartList" :key="i.id">
<td>
<el-checkbox />
</td>
<td>
<div class="goods">
<RouterLink to="/"><img :src="i.picture" alt="" /></RouterLink>
<div>
<p class="name ellipsis">
{{ i.name }}
</p>
</div>
</div>
</td>
<td class="tc">
<p>¥{{ i.price }}</p>
</td>
<td class="tc">
<el-input-number v-model="i.count" :min="1" />
</td>
<td class="tc">
<p class="f16 red">¥{{ (i.price * i.count).toFixed(2) }}</p>
</td>
<td class="tc">
<p>
<el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消" @confirm="">
<template #reference>
<a href="javascript:;">删除</a>
</template>
</el-popconfirm>
</p>
</td>
</tr>
<tr v-if="cartList.length === 0">
<td colspan="6">
<div class="cart-none">
<el-empty description="购物车列表为空">
<el-button type="primary">随便逛逛</el-button>
</el-empty>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 操作栏 -->
<div class="action">
<div class="batch">
共 10 件商品,已选择 2 件,商品合计:
<span class="red">¥ 200.00 </span>
</div>
<div class="total">
<el-button size="large" type="primary" >下单结算</el-button>
</div>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
.xtx-cart-page {
margin-top: 20px;
.cart {
background: #fff;
color: #666;
table {
border-spacing: 0;
border-collapse: collapse;
line-height: 24px;
th,
td {
padding: 10px;
border-bottom: 1px solid #f5f5f5;
&:first-child {
text-align: left;
padding-left: 30px;
color: #999;
}
}
th {
font-size: 16px;
font-weight: normal;
line-height: 50px;
}
}
}
.cart-none {
text-align: center;
padding: 120px 0;
background: #fff;
p {
color: #999;
padding: 20px 0;
}
}
.tc {
text-align: center;
a {
color: $xtxColor;
}
.xtx-numbox {
margin: 0 auto;
width: 120px;
}
}
.red {
color: $priceColor;
}
.green {
color: $xtxColor;
}
.f16 {
font-size: 16px;
}
.goods {
display: flex;
align-items: center;
img {
width: 100px;
height: 100px;
}
>div {
width: 280px;
font-size: 16px;
padding-left: 10px;
.attr {
font-size: 14px;
color: #999;
}
}
}
.action {
display: flex;
background: #fff;
margin-top: 20px;
height: 80px;
align-items: center;
font-size: 16px;
justify-content: space-between;
padding: 0 30px;
.xtx-checkbox {
color: #999;
}
.batch {
a {
margin-left: 20px;
}
}
.red {
font-size: 18px;
margin-right: 20px;
font-weight: bold;
}
}
.tit {
color: #666;
font-size: 16px;
font-weight: normal;
line-height: 50px;
}
}
</style>
重构router/index.js
import CartList from '@/views/CartList/index.vue'
...
{
path: 'cartlist',
component: CartList
}
重构HeaderCart
<div class="foot">
<div class="total">
<p>共 {{allCount}} 件商品</p>
<p>¥ {{allPrice.toFixed(2)}} </p>
</div>
<el-button size="large" type="primary" @click="$router.push('/cartlist')">去购物车结算</el-button>
</div>
</div>
<script setup>
import { useCartStore } from '@/stores/cartStore'
const cartStore = useCartStore()
</script>
...
基本思想:通过skuId找到要进行单选操作的商品,把控制是否选中的selected字段修改为当前单选框的状态
1-重构CartList/index.vue
<tr v-for="i in cartStore.cartList" :key="i.id">
<td>
<el-checkbox v-model="i.selected" />
</td>
###老方法实现
1- 重构cartStore.js
// 单选功能
const singleCheck = (skuId, selected) => {
// 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
const item = cartList.value.find((item) => item.skuId === skuId)
item.selected = selected
}
2- 重构CartList/index.vue
<script setup>
// 单选回调
const singleCheck = (i, selected) => {
console.log(i, selected)
cartStore.singleCheck(i.skuId, selected)
}
</script>
<template>
<td>
<!-- 单选框 -->
<el-checkbox :model-value="i.selected" @change="(selected) => singleCheck(i, selected)" />
</td>
</template>
基础思想:
- 全选状态决定单选框状态 - 遍历cartList把每一项的selected都设置为何全选框状态一致
- 单选框状态决定全选状态 - 只有所有单选框的selected都为true, 全选框才为true
1- store中定义action和计算属性
// 全选功能
const checkAll = (selected) => {
// 把cartList中的每一项的selected都设置为当前的全选框状态
cartList.value.forEach(item => item.selected = selected)
}
// 3. 是否全选计算属性
const isAll = computed(() => cartList.value.every((item) => item.selected))
return{
//暴露属性
...
isAll,
//暴露方法
...
allCheck
}
2- 组件中触发aciton和使用计算属性
<template>
<!-- 全选框 -->
<el-checkbox :model-value="cartStore.isAll" @change="cartStore.checkAll" />
</template>
重构store
// 4. 已选择数量
const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
// 5. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
return{
//暴露属性
...
selectedCount,
selectedPrice,
//暴露方法
...
}
重构vue
<!-- 操作栏 -->
<div class="action">
<div class="batch">
共 {{ cartStore.allCount }} 件商品,已选择 {{ cartStore.selectedCount }} 件,商品合计:
<span class="red">¥ {{cartStore.selectedPrice.toFixed(2)}} </span>
</div>
<div class="total">
<el-button size="large" type="primary" >下单结算</el-button>
</div>
</div>
创建apis/cart.js
注意之前在utils/http.js的请求拦截器中加了token配置,所以登录后,所有操作会从token信息中获取user信息
import http from "@/utils/http";
/**
* @description: 获取最新的购物车列表
* @param {*}
* @return {*}
*/
export function findNewCartListAPI(){
return http.get('/member/cart');
}
/**
* @description: 根据sku对象进行新增购物车
* @param {sku} 用户对象
* @return {*}
*/
export function insertCartAPI(sku){
return http.post('/member/cart',sku);
}
import {defineStore} from "pinia";
import {ref,computed} from "vue";
import {useUserStore} from "@/stores/userStore";
import {findNewCartListAPI, insertCartAPI} from "@/apis/cart";
export const useCartStore = defineStore('cart',()=>{
const cartList = ref([]);
const userStore = useUserStore();
const isLogin = computed(()=>userStore.userInfo.token);
// 获取登录后最新购物车列表action
const updateLoginCartList = async () => {
const res = await findNewCartListAPI()
cartList.value = res.result
}
const addCart = async (goods)=>{
if(isLogin.value){
//登录之后加入购物车逻辑
await insertCartAPI(goods)
updateLoginCartList()
}else {
//判断商品是否在购物车
const item = cartList.value.find(item => goods.skuId === item.skuId);
if (item) {
item.count += goods.count
} else {
cartList.value.push(goods)
}
}
}
return{
...
updateLoginCartList
}
export const useUserStore = defineStore(
'user',
() => {
// 1. 定义管理用户数据的state
const userInfo = ref({})
const cartStore = useCartStore();
// 2. 定义获取接口数据的action函数
const getUserInfo = async (user) => {
const res = await loginAPI(user)
userInfo.value = res.result
await cartStore.updateLoginCartList()
}
重构cart.js
/**
* @description: 根据ids删除购物车
* @param {*}
* @return {*}
*/
export const delCartAPI = (ids) => {
return http.delete('/member/cart',{data:{ids}})
}
###步骤2:新增删除购物车store
重构cartStore.js
// 删除购物项
const delCart = async (skuId) => {
if(isLogin.value){
//登录之后加入购物车逻辑
console.log([skuId])
await delCartAPI([skuId])
updateNewList()
}else {
// 思路:
// 1. 找到要删除项的下标值 - splice
// 2. 使用splice删除找到的项,原数组改变
const idx = cartList.value.findIndex((item) => skuId === item.skuId)
cartList.value.splice(idx, 1)
}
}
重构cartStore.js
// 清除购物车
const clearCart = () => {
cartList.value = []
}
return{
//暴露属性
...
//暴露方法
...
clearCart
}
重构userStore.js
const cartStore = useCartStore();
...
// 退出时清除用户信息
const clearUserInfo = () => {
userInfo.value = {}
cartStore.clearCart()
}
重构apis/cart.js
//合并购物车
export function mergeCartAPI(data){
return http.post('/member/cart/merge',data);
}
// 2. 定义获取接口数据的action函数
const getUserInfo = async (user) => {
const res = await loginAPI(user)
userInfo.value = res.result
//合并购物车
await mergeCartAPI(cartStore.cartList.map(item=>{
return{
skuId: item.skuId,
selected: item.selected,
count: item.count
}
}))
//刷新购物车列表
cartStore.updateNewList();
}
重构cart.js,新增updateCartItem
//修改购物项
export function updateCartItem(skuId,data){
return http.put(`/member/cart/${skuId}`,data);
}
###步骤2:重构cartStore.js
//修改购物项
const updateCartItem = async (goods) => {
const {skuId,count,selected} = goods
if (isLogin.value) {
await updateCartItem(skuId,{count,selected})
}
}
return {
...
updateCartItem
}
<td>
<el-checkbox v-model="i.selected" @change="cartStore.updateCart(i)" />
</td>
...
<td class="tc">
<el-input-number v-model="i.count" :min="1" @change="cartStore.updateCart(i)" />
</td>