一、本地购物车 - 列表购物车
1. 基础内容渲染
①准备模板 - src/views/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" />
</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="delCart(i)"
>
<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>
②绑定路由关系 - src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
// ... ...
import CartList from '@/views/cartList/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
component: Layout,
children: [
// ... ...
{
path: 'cartlist',
component: CartList
}
]
},
{
path: '/login',
component: Login
}
],
// 路由滚动行为定制
scrollBehavior() {
return {
top: 0
}
}
})
export default router
③src/views/Layout/components/HeaderCart.vue
<el-button
@click="$router.push('/cartlist')"
size="large"
type="primary"
>去购物车结算</el-button
>
④渲染列表
<script setup>
import { useCartStore } from '@/stores/cart.js'
const cartStore = useCartStore()
</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 cartStore.cartList" :key="i.id">
<td>
<!-- 单选框 -->
<el-checkbox
:model-value="i.selected"
/>
</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" />
</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="cartStore.delCart(i)"
>
<template #reference>
<a href="javascript:;">删除</a>
</template>
</el-popconfirm>
</p>
</td>
</tr>
<tr v-if="cartStore.cartList.length === 0">
<td colspan="6">
<div class="cart-none">
<el-empty description="购物车列表为空">
<el-button @click="$router.push('/')" type="primary"
>随便逛逛</el-button
>
</el-empty>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 操作栏 -->
<div class="action">
<div class="batch">
共 {{ cartStore.allCount }} 件商品,已选择 2 件,商品合计:
<span class="red">¥ 200.00 </span>
</div>
<div class="total">
<el-button size="large" type="primary">下单结算</el-button>
</div>
</div>
</div>
</div>
</template>
2. 单选功能
核心思路:单选的核心思路就是始终把单选框的状态和Pinia中store对应的状态保持同步
注意事项:v-model双向绑定指令不方便进行命令式的操作(因为后续还需要调用接口),所以把v-model回退到一般模式,也就是 :model-value 和 @change 的配合实现
①添加单选action - src/stores/cart.js
// 单选功能
const singleCheck = (skuId, selected) => {
// 通过skuId找到要修改的那一项,然后把他的selected修改为传过来的selected
const item = cartList.value.find((item) => item.skuId === skuId)
item.selected = selected
}
②触发action函数 - src/views/cartList/index.vue
<script setup>
// 单选回调
const singleCheck = (i, selected) => {
console.log(i, selected)
// store cartList 数组 无法知道要修改谁的选中状态?
// 除了selected补充一个用来筛选的参数 - skuId
cartStore.singleCheck(i.skuId, selected)
}
</script>
<template>
<td>
<!-- 单选框 -->
<el-checkbox :model-value="i.selected" @change="(selected) => singleCheck(i, selected)" />
</td>
</template>
3. 全选功能
核心思路:
- 1. 操作单选决定全选:只有当cartList中的所有项都为true时,全选状态才为true
- 2. 操作全选决定单选:cartList中的所有项的selected都要跟着一起变
①定义action和计算属性 - src/stores/cart.js
// 全选功能
const allCheck = (selected) => {
// 把cartList中的每一项的selected都设置为当前的全选框状态
cartList.value.forEach((item) => (item.selected = selected))
}
// 判断是否全选计算属性
const isAll = computed(
() =>
cartList.value.length > 0 &&
cartList.value.every((item) => item.selected)
)
②组件中触发action和使用计算属性 - src/views/cartList/index.vue
<script setup>
const allCheck = (selected) => {
cartStore.allCheck(selected)
}
</script>
<template>
<!-- 全选框 -->
<el-checkbox :model-value="cartStore.isAll" @change="allCheck" />
</template>
4. 统计数据功能实现
①定义计算属性 - src/stores/cart.js
// 3. 已选择数量
const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
// 4. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))
②组件中使用 - src/views/cartList/index.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>
二、 接口购物车
结论:到目前为止,购物车在非登录状态下的各种操作都已经ok了,包括action的封装、触发、参数传递,剩下的事情就是在action中做登录状态的分支判断,补充登录状态下的接口操作逻辑即可。
1. 加入购物车
①封装接口 - src/apis/cart.js
import instance from '@/utils/http.js'
// 加入购物车
export const insertCartAPI = ({ skuId, count }) => {
return instance({
url: '/member/cart',
method: 'POST',
data: {
skuId,
count
}
})
}
// 获取购物车列表
export const updateNewListAPI = () => {
return instance({
url: '/member/cart'
})
}
②action中适配登录和非登录
import { defineStore } from 'pinia'
import { useUserStore } from './user.js'
import { insertCartAPI, updateNewListAPI } from '@/apis/cart.js'
export const useCartStore = defineStore('cart', () => {
const userStore = useUserStore()
const isLogin = computed(() => userStore.userInfo.token)
const addCart = async (goods) => {
const { skuId, count } = goods
// 登录
if (isLogin.value) {
// 登录之后的加入购车逻辑
await insertCartAPI({ skuId, count })
const res = await updateNewListAPI()
cartList.value = res.result
} else {
// 未登录
const item = cartList.value.find((item) => goods.skuId === item.skuId)
if (item) {
// 找到了
item.count++
} else {
// 没找到
cartList.value.push(goods)
}
}
}
}, {
persist: true,
})
2. 删除购物车
①封装接口 - src/apis/cart.js
// 删除购物车
export const delCartAPI = (ids) => {
return instance({
url: '/member/cart',
method: 'DELETE',
data: {
ids
}
})
}
②action中适配登录和非登录 - src/stores/cart.js
// 删除购物车
const delCart = async (skuId) => {
if (isLogin.value) {
// 调用接口实现接口购物车的删除功能
await delCartAPI([skuId])
updateNewList()
} else {
// 思路:1. 找到要删除的下标值 - splice
// 2. 使用组件的过滤方法 - filter
const idx = cartList.value.findIndex((item) => skuId === item.skuId)
cartList.value.splice(idx, 1)
}
}
// 获取最新购物车列表action
const updateNewList = async () => {
const res = await updateNewListAPI()
cartList.value = res.result
}
三、退出登录 - 清空购物车列表
1. 业务需求
在用户退出登录时,除了清空用户信息之外,也需要把购物车数据清空
①封装接口 - src/stores/cart.js
// 清除购物车
const clearCart = () => {
cartList.value = []
}
②在退出登录action中执行清除业务 - src/stores/user.js
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user'
import { ref } from 'vue'
import { useCartStore } from './cart.js'
export const useUserStore = defineStore(
'user',
() => {
// 1. 定义管理用户数据的state
const userInfo = ref({})
const cartStore = useCartStore()
// 2. 定义获取数据的action函数
const getUserInfo = async ({ account, password }) => {
const res = await loginAPI({ account, password })
userInfo.value = res.result
}
// 退出登录时清除用户信息和清空购物车
const clearUserInfo = () => {
userInfo.value = {}
cartStore.clearCart()
}
// 3. 以对象的形式把state和action return
return {
userInfo,
getUserInfo,
clearUserInfo
}
},
{
persist: true
}
)
四、合并本地购物车到服务器
1. 合并购物车业务实现
问:用户在非登录时进行的所有购物车操作,我们的服务器能知道吗?
答:不能。不能的话不是白操作了吗?本地购物车的意义在哪?
解决办法:在用户登录时,把本地购物车数据和服务器端购物车数据进行合并操作。
①封装接口 - src/apis/cart.js
// 合并购物车
export const mergeCartAPI = (data) => {
return instance({
url: '/member/cart/merge',
method: 'POST',
data: data
})
}
②登录时调用合并购物车接口,获取最新的购物车列表,覆盖本地的购物车列表
src/stores/user.js
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user'
import { ref } from 'vue'
import { useCartStore } from './cart.js'
import { mergeCartAPI } from '@/apis/cart.js'
export const useUserStore = defineStore(
'user',
() => {
// 1. 定义管理用户数据的state
const userInfo = ref({})
const cartStore = useCartStore()
// 2. 定义获取数据的action函数
const getUserInfo = async ({ account, password }) => {
const res = await loginAPI({ account, password })
userInfo.value = res.result
// 合并购物车
await mergeCartAPI(
cartStore.cartList.map((item) => {
return {
skuId: item.skuId,
selected: item.selected,
count: item.count
}
})
)
cartStore.updateNewList()
}
// 退出登录时清除用户信息和清空购物车
const clearUserInfo = () => {
userInfo.value = {}
cartStore.clearCart()
}
// 3. 以对象的形式把state和action return
return {
userInfo,
getUserInfo,
clearUserInfo
}
},
{
persist: true
}
)
五、结算模块 - 路由配置和基础数据渲染
1. 路由陪着和基础数据渲染
路由配置:
①准备组件 - src/views/Checkout/index.vue
<script setup>
const checkInfo = {} // 订单对象
const curAddress = {} // 地址对象
</script>
<template>
<div class="xtx-pay-checkout-page">
<div class="container">
<div class="wrapper">
<!-- 收货地址 -->
<h3 class="box-title">收货地址</h3>
<div class="box-body">
<div class="address">
<div class="text">
<div class="none" v-if="!curAddress">
您需要先添加收货地址才可提交订单。
</div>
<ul v-else>
<li>
<span>收<i />货<i />人:</span>{{ curAddress.receiver }}
</li>
<li><span>联系方式:</span>{{ curAddress.contact }}</li>
<li>
<span>收货地址:</span>{{ curAddress.fullLocation }}
{{ curAddress.address }}
</li>
</ul>
</div>
<div class="action">
<el-button size="large" @click="toggleFlag = true"
>切换地址</el-button
>
<el-button size="large" @click="addFlag = true"
>添加地址</el-button
>
</div>
</div>
</div>
<!-- 商品信息 -->
<h3 class="box-title">商品信息</h3>
<div class="box-body">
<table class="goods">
<thead>
<tr>
<th width="520">商品信息</th>
<th width="170">单价</th>
<th width="170">数量</th>
<th width="170">小计</th>
<th width="170">实付</th>
</tr>
</thead>
<tbody>
<tr v-for="i in checkInfo.goods" :key="i.id">
<td>
<a href="javascript:;" class="info">
<img :src="i.picture" alt="" />
<div class="right">
<p>{{ i.name }}</p>
<p>{{ i.attrsText }}</p>
</div>
</a>
</td>
<td>¥{{ i.price }}</td>
<td>{{ i.price }}</td>
<td>¥{{ i.totalPrice }}</td>
<td>¥{{ i.totalPayPrice }}</td>
</tr>
</tbody>
</table>
</div>
<!-- 配送时间 -->
<h3 class="box-title">配送时间</h3>
<div class="box-body">
<a class="my-btn active" href="javascript:;"
>不限送货时间:周一至周日</a
>
<a class="my-btn" href="javascript:;">工作日送货:周一至周五</a>
<a class="my-btn" href="javascript:;">双休日、假日送货:周六至周日</a>
</div>
<!-- 支付方式 -->
<h3 class="box-title">支付方式</h3>
<div class="box-body">
<a class="my-btn active" href="javascript:;">在线支付</a>
<a class="my-btn" href="javascript:;">货到付款</a>
<span style="color: #999">货到付款需付5元手续费</span>
</div>
<!-- 金额明细 -->
<h3 class="box-title">金额明细</h3>
<div class="box-body">
<div class="total">
<dl>
<dt>商品件数:</dt>
<dd>{{ checkInfo.summary?.goodsCount }}件</dd>
</dl>
<dl>
<dt>商品总价:</dt>
<dd>¥{{ checkInfo.summary?.totalPrice.toFixed(2) }}</dd>
</dl>
<dl>
<dt>运<i></i>费:</dt>
<dd>¥{{ checkInfo.summary?.postFee.toFixed(2) }}</dd>
</dl>
<dl>
<dt>应付总额:</dt>
<dd class="price">
{{ checkInfo.summary?.totalPayPrice.toFixed(2) }}
</dd>
</dl>
</div>
</div>
<!-- 提交订单 -->
<div class="submit">
<el-button type="primary" size="large">提交订单</el-button>
</div>
</div>
</div>
</div>
<!-- 切换地址 -->
<!-- 添加地址 -->
</template>
<style scoped lang="scss">
.xtx-pay-checkout-page {
margin-top: 20px;
.wrapper {
background: #fff;
padding: 0 20px;
.box-title {
font-size: 16px;
font-weight: normal;
padding-left: 10px;
line-height: 70px;
border-bottom: 1px solid #f5f5f5;
}
.box-body {
padding: 20px 0;
}
}
}
.address {
border: 1px solid #f5f5f5;
display: flex;
align-items: center;
.text {
flex: 1;
min-height: 90px;
display: flex;
align-items: center;
.none {
line-height: 90px;
color: #999;
text-align: center;
width: 100%;
}
> ul {
flex: 1;
padding: 20px;
li {
line-height: 30px;
span {
color: #999;
margin-right: 5px;
> i {
width: 0.5em;
display: inline-block;
}
}
}
}
> a {
color: $xtxColor;
width: 160px;
text-align: center;
height: 90px;
line-height: 90px;
border-right: 1px solid #f5f5f5;
}
}
.action {
width: 420px;
text-align: center;
.btn {
width: 140px;
height: 46px;
line-height: 44px;
font-size: 14px;
&:first-child {
margin-right: 10px;
}
}
}
}
.goods {
width: 100%;
border-collapse: collapse;
border-spacing: 0;
.info {
display: flex;
text-align: left;
img {
width: 70px;
height: 70px;
margin-right: 20px;
}
.right {
line-height: 24px;
p {
&:last-child {
color: #999;
}
}
}
}
tr {
th {
background: #f5f5f5;
font-weight: normal;
}
td,
th {
text-align: center;
padding: 20px;
border-bottom: 1px solid #f5f5f5;
&:first-child {
border-left: 1px solid #f5f5f5;
}
&:last-child {
border-right: 1px solid #f5f5f5;
}
}
}
}
.my-btn {
width: 228px;
height: 50px;
border: 1px solid #e4e4e4;
text-align: center;
line-height: 48px;
margin-right: 25px;
color: #666666;
display: inline-block;
&.active,
&:hover {
border-color: $xtxColor;
}
}
.total {
dl {
display: flex;
justify-content: flex-end;
line-height: 50px;
dt {
i {
display: inline-block;
width: 2em;
}
}
dd {
width: 240px;
text-align: right;
padding-right: 70px;
&.price {
font-size: 20px;
color: $priceColor;
}
}
}
}
.submit {
text-align: right;
padding: 60px;
border-top: 1px solid #f5f5f5;
}
.addressWrapper {
max-height: 500px;
overflow-y: auto;
}
.text {
flex: 1;
min-height: 90px;
display: flex;
align-items: center;
&.item {
border: 1px solid #f5f5f5;
margin-bottom: 10px;
cursor: pointer;
&.active,
&:hover {
border-color: $xtxColor;
background: lighten($xtxColor, 50%);
}
> ul {
padding: 10px;
font-size: 14px;
line-height: 30px;
}
}
}
</style>
②配置路由关系 - src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
// ... ...
import Checkout from '@/views/Checkout/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
component: Layout,
children: [
// ... ...
{
path: 'checkout',
component: Checkout
}
]
},
{
path: '/login',
component: Login
}
],
// 路由滚动行为定制
scrollBehavior() {
return {
top: 0
}
}
})
export default router
③配置路由跳转 - src/views/cartList/index.vue
<div class="total">
<el-button
@click="$router.push('/checkout')"
:disabled="cartStore.cartList.length === 0"
size="large"
type="primary"
>下单结算</el-button
>
</div>
基础数据渲染:
①准备接口 - src/apis/checkout.js
import instance from '@/utils/http.js'
// 获取结算信息
export const getCheckoutInfoAPI = () => {
return instance({
url: '/member/order/pre'
})
}
②获取数据,渲染默认地址和商品列表以及统计数据 - src/views/Checkout/index.vue
<script setup>
import { ref } from 'vue'
import { getCheckoutInfoAPI } from '@/apis/checkout.js'
const checkInfo = ref({}) // 订单对象
const curAddress = ref({})
const getCheckInfo = async () => {
const res = await getCheckoutInfoAPI()
checkInfo.value = res.result
// console.log(checkInfo.value)
// 适配默认地址(从地址列表中筛选出来isDefault === 0 的那一项
const item = checkInfo.value.userAddresses.find(
(item) => item.isDefault === 0
)
curAddress.value = item
}
getCheckInfo()
</script>
六、结算模块 - 地址切换交互实现
1. 地址切换交互需求分析
①打开弹框交互:点击切换地址按钮,打开弹框,回显用户可选地址列表
②切换地址交互:点击切换地址,点击确认按钮,激活地址替换默认收货地址
2. 打开弹框交互
①准备弹框组件 - src/views/Checkout/index.vue
<el-dialog title="切换收货地址" width="30%" center>
<div class="addressWrapper">
<div class="text item" v-for="item in checkInfo.userAddresses" :key="item.id">
<ul>
<li><span>收<i />货<i />人:</span>{{ item.receiver }} </li>
<li><span>联系方式:</span>{{ item.contact }}</li>
<li><span>收货地址:</span>{{ item.fullLocation + item.address }}</li>
</ul>
</div>
</div>
<template #footer>
<span class="dialog-footer">
<el-button>取消</el-button>
<el-button type="primary">确定</el-button>
</span>
</template>
</el-dialog>
②组件v-model绑定响应式数据 - src/views/Checkout/index.vue
const showDialog = ref(false)
<el-button size="large" @click="showDialog = true">切换地址</el-button>
<el-dialog v-model="showDialog" title="切换收货地址" width="30%" center>
<!-- 省略 -->
</el-dialog>
2. 切换地址交互
原理:地址切换是我们经常遇到的`tab切换类`需求,这类需求的实现逻辑都是相似的
- 1. 点击时记录一个当前激活地址对象activeAddress,点击哪个地址就把哪个地址对象记录下来
- 2. 通过动态类名 :class 控制激活样式类型active是否存在,判断条件为:激活地址对象的id === 当前项id
src/views/Checkout/index.vue
<script setup>
// 切换地址
const activeAddress = ref({})
const switchAddress = (item) => {
activeAddress.value = item
}
// 点击确认
const confirm = () => {
curAddress.value = activeAddress.value
showDialog.value = false
}
</script>
<template>
<div class="text item"
:class="{ active: activeAddress.id === item.id }"
@click="switchAddress(item)"
:key="item.id">
<!-- 省略... -->
</div>
<!-- ... ... -->
<template #footer>
<span class="dialog-footer">
<el-button @click="showDialog = false">取消</el-button>
<el-button @click="confirm" type="primary">确定</el-button>
</span>
</template>
</template>
七、订单模块 - 生成订单功能实现
1. 业务需求说明
确定结算信息没有问题之后,点击提交订单按钮,需要做以下两个事情:
- 1. 调用接口生成订单id,并且携带id跳转到支付页
- 2. 调用更新购物车列表接口,更新购物车状态
①准备支付页组件 - src/views/Pay/index.vue
<script setup>
const payInfo = {}
</script>
<template>
<div class="xtx-pay-page">
<div class="container">
<!-- 付款信息 -->
<div class="pay-info">
<span class="icon iconfont icon-queren2"></span>
<div class="tip">
<p>订单提交成功!请尽快完成支付。</p>
<p>支付还剩 <span>24分30秒</span>, 超时后将取消订单</p>
</div>
<div class="amount">
<span>应付总额:</span>
<span>¥{{ payInfo.payMoney?.toFixed(2) }}</span>
</div>
</div>
<!-- 付款方式 -->
<div class="pay-type">
<p class="head">选择以下支付方式付款</p>
<div class="item">
<p>支付平台</p>
<a class="btn wx" href="javascript:;"></a>
<a class="btn alipay" :href="payUrl"></a>
</div>
<div class="item">
<p>支付方式</p>
<a class="btn" href="javascript:;">招商银行</a>
<a class="btn" href="javascript:;">工商银行</a>
<a class="btn" href="javascript:;">建设银行</a>
<a class="btn" href="javascript:;">农业银行</a>
<a class="btn" href="javascript:;">交通银行</a>
</div>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
.xtx-pay-page {
margin-top: 20px;
}
.pay-info {
background: #fff;
display: flex;
align-items: center;
height: 240px;
padding: 0 80px;
.icon {
font-size: 80px;
color: #1dc779;
}
.tip {
padding-left: 10px;
flex: 1;
p {
&:first-child {
font-size: 20px;
margin-bottom: 5px;
}
&:last-child {
color: #999;
font-size: 16px;
}
}
}
.amount {
span {
&:first-child {
font-size: 16px;
color: #999;
}
&:last-child {
color: $priceColor;
font-size: 20px;
}
}
}
}
.pay-type {
margin-top: 20px;
background-color: #fff;
padding-bottom: 70px;
p {
line-height: 70px;
height: 70px;
padding-left: 30px;
font-size: 16px;
&.head {
border-bottom: 1px solid #f5f5f5;
}
}
.btn {
width: 150px;
height: 50px;
border: 1px solid #e4e4e4;
text-align: center;
line-height: 48px;
margin-left: 30px;
color: #666666;
display: inline-block;
&.active,
&:hover {
border-color: $xtxColor;
}
&.alipay {
background: url(https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/7b6b02396368c9314528c0bbd85a2e06.png) no-repeat center / contain;
}
&.wx {
background: url(https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/c66f98cff8649bd5ba722c2e8067c6ca.jpg) no-repeat center / contain;
}
}
}
</style>
②绑定路由 - src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
// ... ...
import Pay from '@/views/Pay/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
component: Layout,
children: [
// ... ...
{
path: 'pay',
component: Pay
}
]
},
{
path: '/login',
component: Login
}
],
// 路由滚动行为定制
scrollBehavior() {
return {
top: 0
}
}
})
export default router
③封装生成订单接口 - src/apis/checkout.js
// 创建订单
export const createOrderAPI = (data) => {
return instance({
url: '/member/order',
method: 'POST',
data
})
}
④绑定路由跳转关系 - src/views/Checkout/index.vue
<script setup>
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart.js'
// 创建订单
const router = useRouter()
const cartStore = useCartStore()
const createOrder = async () => {
const res = await createOrderAPI({
deliveryTimeType: 1,
payType: 1,
payChannel: 1,
buyerMessage: '',
goods: checkInfo.value.goods.map((item) => {
return {
skuId: item.skuId,
count: item.count
}
}),
addressId: curAddress.value.id
})
const orderId = res.result.id
router.push({
path: '/pay',
query: {
id: orderId
}
})
// 更新购物车
cartStore.updateNewList()
}
</script>
<template>
<!-- 提交订单 -->
<div class="submit">
<el-button @click="createOrder" type="primary" size="large"
>提交订单</el-button
>
</div>
</template
八、支付模块 - 渲染基础数据
支付页有两个关键数据,一个是要支付的金额,一个是倒计时数据(超时不支付商品释放)
①封装获取订单详情的接口 - src/apis/pay.js
import instance from '@/utils/http'
// 获取订单详情
export const getOrderAPI = (id) => {
return instance({
url: `/member/order/${id}`
})
}
②获取数据渲染内容 - src/views/Pay/index.vue
<script setup>
import { getOrderAPI } from '@/apis/pay'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
// 获取订单数据
const route = useRoute()
const payInfo = ref({})
const getPayInfo = async () => {
const res = await getOrderAPI(route.query.id)
payInfo.value = res.result
}
getPayInfo()
</script>
<template>
<div class="xtx-pay-page">
<div class="container">
<!-- 付款信息 -->
<div class="pay-info">
<span class="icon iconfont icon-queren2"></span>
<div class="tip">
<p>订单提交成功!请尽快完成支付。</p>
<p>支付还剩 <span>{{ formatTime }}</span>, 超时后将取消订单</p>
</div>
<div class="amount">
<span>应付总额:</span>
<span>¥{{ payInfo.payMoney?.toFixed(2) }}</span>
</div>
</div>
<!-- 付款方式 -->
<div class="pay-type">
<p class="head">选择以下支付方式付款</p>
<div class="item">
<p>支付平台</p>
<a class="btn wx" href="javascript:;"></a>
<a class="btn alipay" :href="payUrl"></a>
</div>
<div class="item">
<p>支付方式</p>
<a class="btn" href="javascript:;">招商银行</a>
<a class="btn" href="javascript:;">工商银行</a>
<a class="btn" href="javascript:;">建设银行</a>
<a class="btn" href="javascript:;">农业银行</a>
<a class="btn" href="javascript:;">交通银行</a>
</div>
</div>
</div>
</div>
</template>
九、支付模块 - 实现支付功能
1. 支付业务流程
src/views/Pay/index.vue
<script setup>
// 跳转支付
// 携带订单id以及回跳地址,跳转到支付地址(get)
// 支付地址
const baseURL = 'http://pcapi-xiaotuxian-front-devtest.itheima.net/'
const backURL = 'http://127.0.0.1:5173/paycallback'
const redirectUrl = encodeURIComponent(backURL)
const payUrl = `${baseURL}pay/aliPay?orderId=${route.query.id}&redirect=${redirectUrl}`
</script>
账号已经没钱了!!!
十、支付模块 - 支付结果展示
①准备模板 - src/views/Pay/PayBack.vue
<script setup></script>
<template>
<div class="xtx-pay-page">
<div class="container">
<!-- 支付结果 -->
<div class="pay-result">
<span class="iconfont icon-queren2 green"></span>
<span class="iconfont icon-shanchu red"></span>
<p class="tit">支付成功</p>
<p class="tip">我们将尽快为您发货,收货期间请保持手机畅通</p>
<p>支付方式:<span>支付宝</span></p>
<p>支付金额:<span>¥200.00</span></p>
<div class="btn">
<el-button type="primary" style="margin-right: 20px"
>查看订单</el-button
>
<el-button>进入首页</el-button>
</div>
<p class="alert">
<span class="iconfont icon-tip"></span>
温馨提示:小兔鲜儿不会以订单异常、系统升级为由要求您点击任何网址链接进行退款操作,保护资产、谨慎操作。
</p>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
.pay-result {
padding: 100px 0;
background: #fff;
text-align: center;
margin-top: 20px;
> .iconfont {
font-size: 100px;
}
.green {
color: #1dc779;
}
.red {
color: $priceColor;
}
.tit {
font-size: 24px;
}
.tip {
color: #999;
}
p {
line-height: 40px;
font-size: 16px;
}
.btn {
margin-top: 50px;
}
.alert {
font-size: 12px;
color: #999;
margin-top: 50px;
}
}
</style>
②绑定路由 - src/router/index.vue
import { createRouter, createWebHistory } from 'vue-router'
// ... ...
import PayBack from '@/views/Pay/PayBack.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
component: Layout,
children: [
// ... ...
{
path: 'paycallback',
component: PayBack
}
]
},
{
path: '/login',
component: Login
}
],
// 路由滚动行为定制
scrollBehavior() {
return {
top: 0
}
}
})
export default router
③渲染数据 - src/views/Pay/PayBack.vue
<script setup>
import { ref } from 'vue'
import { getOrderAPI } from '@/apis/pay.js'
import { useRoute } from 'vue-router'
const route = useRoute()
const orderInfo = ref({})
const getOrderInfo = async () => {
const res = await getOrderAPI(route.query.orderId)
orderInfo.value = res.result
}
getOrderInfo()
</script>
<template>
<div class="xtx-pay-page">
<div class="container">
<!-- 支付结果 -->
<div class="pay-result">
<!-- 路由参数获取到的是字符串而不是布尔值 -->
<span
class="iconfont icon-queren2 green"
v-if="$route.query.payResult === 'true'"
></span>
<span class="iconfont icon-shanchu red" v-else></span>
<p class="tit">
支付{{ $route.query.payResult === 'true' ? '成功' : '失败' }}
</p>
<p class="tip">我们将尽快为您发货,收货期间请保持手机畅通</p>
<p>支付方式:<span>支付宝</span></p>
<p>
支付金额:<span>¥{{ orderInfo.payMoney?.toFixed(2) }}</span>
</p>
<div class="btn">
<el-button type="primary" style="margin-right: 20px"
>查看订单</el-button
>
<el-button @click="$router.push('/')">进入首页</el-button>
</div>
<p class="alert">
<span class="iconfont icon-tip"></span>
温馨提示:小兔鲜儿不会以订单异常、系统升级为由要求您点击任何网址链接进行退款操作,保护资产、谨慎操作。
</p>
</div>
</div>
</div>
</template>
十一、封装倒计时函数
编写一个函数useCountDown 可以把秒数格式化为倒计时的显示状态,函数使用样例如下:
const { formatTime, start } = useCountDown()
{{ formatTime }}
start(60)
1. formatTime为显示的倒计时时间
2. start是倒计时启动函数,调用时可以设置初始值并开始倒计时
①安装dayjs
pnpm add dayjs
②封装倒计时逻辑函数 - src/composables/useCountDown.js
// 封装倒计时逻辑函数
import { ref, computed, onUnmounted } from 'vue'
import dayjs from 'dayjs'
export const useCountDown = () => {
// 1. 响应式的数据
let timer = null
const time = ref(0)
// 格式化时间
const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
// 2. 开启倒计时的函数
const start = (currentTime) => {
// 编写开始倒计时的逻辑
// 核心逻辑:每隔1s就减一
time.value = currentTime
timer = setInterval(() => {
time.value--
}, 1000)
}
// 组件销毁时清除定时器
onUnmounted(() => {
timer && clearInterval(timer)
})
return {
formatTime,
start
}
}