前端Vue小兔鲜儿电商项目实战Day06

一、本地购物车 - 列表购物车

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>&yen;{{ i.price }}</p></td><td class="tc"><el-input-number v-model="i.count" /></td><td class="tc"><p class="f16 red">&yen;{{ (i.price * i.count).toFixed(2) }}</p></td><td class="tc"><p><el-popconfirmtitle="确认删除吗?"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>&yen;{{ i.price }}</p></td><td class="tc"><el-input-number v-model="i.count" /></td><td class="tc"><p class="f16 red">&yen;{{ (i.price * i.count).toFixed(2) }}</p></td><td class="tc"><p><el-popconfirmtitle="确认删除吗?"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修改为传过来的selectedconst 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补充一个用来筛选的参数 - skuIdcartStore.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. 使用组件的过滤方法 - filterconst idx = cartList.value.findIndex((item) => skuId === item.skuId)cartList.value.splice(idx, 1)}}// 获取最新购物车列表actionconst 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. 定义管理用户数据的stateconst 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 returnreturn {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. 定义管理用户数据的stateconst 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 returnreturn {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>&yen;{{ i.price }}</td><td>{{ i.price }}</td><td>&yen;{{ i.totalPrice }}</td><td>&yen;{{ 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.valueshowDialog.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.idrouter.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"><!-- 路由参数获取到的是字符串而不是布尔值 --><spanclass="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 = nullconst time = ref(0)// 格式化时间const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))// 2. 开启倒计时的函数const start = (currentTime) => {// 编写开始倒计时的逻辑// 核心逻辑:每隔1s就减一time.value = currentTimetimer = setInterval(() => {time.value--}, 1000)}// 组件销毁时清除定时器onUnmounted(() => {timer && clearInterval(timer)})return {formatTime,start}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/20671.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vs2019 无法打开QT的UI文件

/* * --------------------------- Microsoft Visual StudioQt5.15.2\5.15.2\msvc2019_64 --------------------------- D:\QT_Project_vs\QtWidgetsApplication1\QtWidgetsApplication1\QtWidgetsApplication1.ui 无法打开文件。 --------------------------- 确定 -------…

基于LQR控制算法的电磁减振控制系统simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 基于LQR控制算法的电磁减振控制系统simulink建模与仿真。仿真输出控制器的收敛曲线。 2.系统仿真结果 3.核心程序与模型 版本&#xff1a;MATLAB2022a 08_029m 4.系统原理…

系统架构设计师【第5章】: 软件工程基础知识 (核心总结)

文章目录 5.1 软件工程5.1.1 软件工程定义5.1.2 软件过程模型5.1.3 敏捷模型5.1.4 统一过程模型&#xff08;RUP&#xff09;5.1.5 软件能力成熟度模型 5.2 需求工程5.2.1 需求获取5.2.2 需求变更5.2.3 需求追踪 5.3 系统分析与设计5.3.1 结构化方法5.3.2 面向对象…

Qt6 mathgl数学函数绘图

1. 程序环境 Qt6.5.1, mingw11.2mathgl 8.0.1: https://sourceforge.net/projects/mathgl/,推荐下载mathgl-8.0.LGPL-mingw.win64.7z,Windows环境尝试自己编译mathgl会缺失一些库,补充完整也可以自己编译,路径"D:\mathgl-8.0.LGPL-mingw.win64\bin"添加至系统环境…

复试不考机试,初试300分以上,上岸稳了?东北林业大学计算机考研考情分析!

东北林业大学&#xff08;Northeast Forestry University&#xff09;&#xff0c;简称东北林大&#xff08;NEFU&#xff09;&#xff0c;位于黑龙江省哈尔滨市&#xff0c;是一所以林科为优势、林业工程为特色的中华人民共和国教育部直属高校&#xff0c;由教育部、国家林业局…

Java多线程--volatile关键字

并发编程的三大特性 可见性有序性原子性 可见性 为什么会有可见性问题&#xff1f; 多核CPU 为了提升CPU效率&#xff0c;设计了L1&#xff0c;L2&#xff0c;L3三级缓存&#xff0c;如图。 如果俩个核几乎同时操作同一块内存&#xff0c;cpu1修改完&#xff0c;当下是对c…

APISIX的安装与测试(springboot服务测试)

安装&#xff1a; 1.1安装依赖&#xff1a; curl https://raw.githubusercontent.com/apache/apisix/master/utils/install-dependencies.sh -sL | bash -1.2 安装 OpenResty yum-config-manager --add-repo https://openresty.org/package/centos/openresty.reposudo yum i…

英语翻译程序,可以对用户自己建立的词汇表进行增删查改

⑴ 自行建立一个包含若干英文单词的词汇表文件&#xff0c;系统初始化时导入内存&#xff0c;用于进行句子翻译。 ⑵ 用户可以输入单词或者句子&#xff0c;在屏幕上显示对应翻译结果。 ⑶ 用户可对词汇表进行添加和删除&#xff0c;并能将更新的词汇表存储到文件中。 #defi…

Adobe Acrobat DC无法卸载

控制版面、电脑管家等均无法卸载&#xff0c;使用自身的remove也不能卸载 解决方法&#xff1a;删除Adobe Acrobat DC的注册表 1、首先打开注册列表&#xff1a; 2、根据圈出来的信息&#xff0c;找到以下路径&#xff1a; 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Inst…

现如今AI大环境究竟怎样?

遇到难题不要怕&#xff01;厚德提问大佬答&#xff01; 厚德提问大佬答10 你是否对AI绘画感兴趣却无从下手&#xff1f;是否有很多疑问却苦于没有大佬解答带你飞&#xff1f;从此刻开始这些问题都将迎刃而解&#xff01;你感兴趣的话题&#xff0c;厚德云替你问&#xff0c;你…

车载电子电器架构 —— 智能座舱技术范围(万字长文精讲)

车载电子电器架构 —— 智能座舱技术范围 我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗你的人和事,多看一眼都是你的不对。非必要不费力证明…

MySQL性能分析工具——EXPLAIN

性能分析工具——EXPLAIN 1、概述 定位了查询慢的SQL之后&#xff0c;我们就可以使用EXPLAIN或DESCRIBE工具做针对性的分析查询语句 。 DESCRIBE语句的使用方法与EXPLAIN语句是一样的&#xff0c;并且分析结果也是一样的。 MySQL中有专门负责优化SELECT语句的优化器模块&…

FreeRTOS基础(五):任务挂起与恢复

今天我们将探讨FreeRTOS中的两个非常重要的函数&#xff1a;任务挂起和恢复函数。在实际的嵌入式系统开发中&#xff0c;我们常常需要在特定条件下暂停某些任务的执行&#xff0c;而在满足某些条件后再恢复这些任务的执行。这就像我们日常生活中的“暂停”和“继续”按钮。无论…

【Kubernetes】Pod理论详解

一、Pod基础概念&#xff1a; Pod是kubernetes中最小的资源管理组件&#xff0c;Pod也是最小化运行容器化应用的资源对象。一个Pod代表着集群中运行的一个进程。kubernetes中其他大多数组件都是围绕着Pod来进行支撑和扩展Pod功能的&#xff0c;例如&#xff0c;用于管理Pod运行…

Unix、Linux 软件包管理快速入门对照

Linux&#xff08;RHEL、Ubuntu&#xff09;或者 Unix&#xff08;macOS、FreeBSD&#xff09;可以参看下表快速入门: 命令功能/系统Darwin (macOS)FreeBSDDebian/UbuntuRHEL&#xff08;dnf yum&#xff09;搜索和查找软件包brew searchpkg searchapt listyum list查看软件包…

生态系统服务功能之碳储量

大家好&#xff0c;这期开始新生态系统服务功能即碳储量的计算&#xff0c;这部分较简单&#xff0c;下面让我们开始吧&#xff01;&#xff01;&#xff01; 碳储量的计算公式 生态系统通过从大气中释放和吸收二氧化碳等温室气体来调节地球气候&#xff0c;而森林、 草原和沼…

Stable Diffusion生成图片的参数查看与抹除方法

前几天分享了几张Stable Diffusion生成的艺术二维码&#xff0c;有同学反映不知道怎么查看图片的参数信息&#xff0c;还有的同学问怎么保护自己的图片生成参数不会泄露&#xff0c;这篇文章就来专门分享如何查看和抹除图片的参数。 查看图片的生成参数 1、打开Stable Diffus…

php反序列化入门

一&#xff0c;php面向对象。 1.面向对象&#xff1a; 以“对象”伪中心的编程思想&#xff0c;把要解决的问题分解成对象&#xff0c;简单理解为套用模版&#xff0c;注重结果。 2.面向过程&#xff1a; 以“整体事件”为中心的编程思想&#xff0c;把解决问题的步骤分析出…

就业班 第四阶段(docker) 2401--5.29 day3 Dockerfile+前后段项目若依ruoyi

通过Dockerfile创建镜像 Docker 提供了一种更便捷的方式&#xff0c;叫作 Dockerfile docker build命令用于根据给定的Dockerfile构建Docker镜像。docker build语法&#xff1a; # docker build [OPTIONS] <PATH | URL | ->1. 常用选项说明 --build-arg&#xff0c;设…

Windows安装Docker

启用虚拟化 打开 勾选Hyper-V 验证 下载Docker Docker官网 阿里云 安装Docker 傻瓜式安装 遇到问题&#xff1a; 打开命令窗口&#xff0c;执行命令&#xff1a; wsl --update升级完成之后点击Restart按钮即可 切换阿里镜像 https://fmkoym4e.mirror.aliyuncs.com