【B站 heima】小兔鮮Vue3 項目學習筆記 Day06

文章目錄

    • 購物車本地
      • 1. 列表購物車基礎數據渲染
      • 2. 列表購物車單選功能
      • 3. 列表購物車全選功能
      • 4. 列表購物車統計列表實現
      • 5. 接口-加入購物車
      • 6. 接口-刪除購物車
      • 7. 退出登錄-清空購物車數據
      • 8. 合并購物車到服務器(重要)
    • 結算
      • 1. 路由配置和基礎數據渲染
      • 2. 地址切換-打開彈框交互實現
      • 3. 切換地址-地址激活交互實現
      • 4. 生成訂單功能實現
    • 支付
      • 1. 渲染基礎數據
      • 2. 實現支付功能
      • 3. 支付結果展示
      • 4. 封裝倒計數函數
    • 小結


購物車本地

1. 列表購物車基礎數據渲染

在這里插入圖片描述

  • 模板 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-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>
  • 綁定路由,二級路由,測試可用
{path: 'cartlist',component: CartList
}

在這里插入圖片描述

頭部購物車點擊 購物車結算 按鈕,跳轉到這個頁面

<el-button size="large" type="primary" @click="$router.push('/cartlist')">去購物車結算</el-button>
  • 渲染列表
<!--cartLsit/index.vue-->
<script setup>
// const cartList = []
import { useCartStore } from '@/stores/cartStore';
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 /></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-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="cartStore.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>

在這里插入圖片描述

2. 列表購物車單選功能

核心思路:單選的核心思路就是始終把單選框的狀態和Piniastore對應的狀態保持同步

注意事項: v-model雙向綁定指令不方便進行命令式的操作(因為后續還需要調用接口),所以把v-model回退到一般模式,也就是:model-value @change 的配合實現

// 單選功能
const singleCheck = (skuId, selected) => {// 通過skuId找到要修改的那一項 然后把它的selected修改為傳過來的selectedconst item = cartList.value.find((item) => item.skuId === skuId)item.selected = selected
}
<!--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. 列表購物車全選功能

基礎思想

  • 全選狀態決定單選框狀態 - 遍歷cartList把每一項的selected都設置為何全選框狀態一致

  • 單選框狀態決定全選狀態 - 只有所有單選框的selected都為true, 全選框才為true

// 全選功能action
const allCheck = (selected) => {// 把cartList中的每一項的selected都設置為當前的全選框狀態cartList.value.forEach(item => item.selected = selected)
}// 是否全選計算屬性
const isAll = computed(() => cartList.value.every((item) => item.selected))
<script setup>
const allCheck = (selected) => {cartStore.allCheck(selected)
}</script><template><!-- 全選框 --><el-checkbox :model-value="cartStore.isAll" @change="allCheck" />
</template>

4. 列表購物車統計列表實現

下面的價格/件數,與之前計算的同理同理

// 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))
 <div class="batch">共 {{ cartStore.allCount }} 件商品,已選擇 {{ cartStore.selectedCount }} 件,商品合計:<span class="red">¥ {{ cartStore.selectedPrice }} </span>
</div>

5. 接口-加入購物車

在這里插入圖片描述

步驟:

  • 找到加入購物車addCartaction,判斷是否是登錄狀態(看token

在這里插入圖片描述

  • 封裝調用加入購物車接口

? apis新增cart.js

import httpInstance from "@/utils/http"//加入購物車
export const insertCartAPI = ({ skuId, count }) => {return httpInstance({url: '/member/cart',method: 'POST',data: {skuId,count}})
}//獲取最新的購物車列表
export const findNewCartListAPI = () => {return httpInstance({url: '/member/cart'})
}
  • 封裝調用獲取購物車列表接口

  • 用接口購物車列表去覆蓋本地購物車列表

// 封裝購物車模塊import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI } from '@/apis/cart.js'export const useCartStore = defineStore('cart', () => {const userStore = useUserStore()//用computed映射一下token,方便數據轉換,響應式更新const isLogin = computed(() => userStore.userInfo.token)// 1. 定義state - cartList購物車列表const cartList = ref([])// 2. 定義action - addCart添加購物車const addCart = async (goods) => {//解構出來const { skuId, count } = goodsif (isLogin.value) {//登錄狀態下//調用加入購物車接口await insertCartAPI({ skuId, count })//調用獲取購物車列表接口const res = await findNewCartListAPI()//覆蓋本地購物車cartList.value = res.result} else {console.log('添加', goods)// 添加購物車操作// 已添加過 - count + 1// 沒有添加過 - 直接push// 思路:通過匹配傳遞過來的商品對象中的skuId能不能在cartList中找到,找到了就是添加過const item = cartList.value.find((item) => goods.skuId === item.skuId)if (item) {// 找到了item.count++} else {// 沒找到cartList.value.push(goods)}}}// 刪除購物車const delCart = async (skuId) => {// 思路:// 1. 找到要刪除項的下標值 - splice// 2. 使用數組的過濾方法 - filterconst idx = cartList.value.findIndex((item) => skuId === item.skuId)cartList.value.splice(idx, 1)}// 單選功能const singleCheck = (skuId, selected) => {// 通過skuId找到要修改的那一項 然后把它的selected修改為傳過來的selectedconst item = cartList.value.find((item) => item.skuId === skuId)item.selected = selected}// 全選功能actionconst allCheck = (selected) => {// 把cartList中的每一項的selected都設置為當前的全選框狀態cartList.value.forEach(item => item.selected = selected)}// 是否全選計算屬性const isAll = computed(() => cartList.value.every((item) => item.selected))//計算購物車件數和總價格//總數const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))//總價const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))// 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))return {cartList,allCount,allPrice,selectedCount,selectedPrice,addCart,delCart,singleCheck,allCheck}
}, {persist: true,
})

6. 接口-刪除購物車

思路和 加入購物車 類似

封裝接口

// 刪除購物車
export const delCartAPI = (ids) => {return httpInstance({url: '/member/cart',method: 'DELETE',data: {ids}})
}

書寫邏輯

  // 刪除購物車const delCart = async (skuId) => {if (isLogin.value) {// 調用接口實現接口購物車中的刪除功能await delCartAPI([skuId])//調用獲取購物車列表接口const res = await findNewCartListAPI()//覆蓋本地購物車cartList.value = res.result} else {// 思路:// 1. 找到要刪除項的下標值 - splice// 2. 使用數組的過濾方法 - filterconst idx = cartList.value.findIndex((item) => skuId === item.skuId)cartList.value.splice(idx, 1)}}

在這里插入圖片描述

  • 優化

    由于更新列表都需要重復使用下面兩行代碼,我們抽象成一個action函數方便使用(雖然就兩行代碼,但我們學習的是這種思想,有些公司就對于代碼的重復度有要求。)

 //獲取最新的購物車列表const updateNewList = async () => {//調用獲取購物車列表接口const res = await findNewCartListAPI()//覆蓋本地購物車cartList.value = res.result}

使用的時候調用updateNewList就可以了

7. 退出登錄-清空購物車數據

  • 清除購物車action,記得return出去
//清空購物車  stores/cartStore.jsconst clearCart = () => {cartList = []}
  • 退出登錄時清除購物車
//退出登錄,數據清空  stores/user.jsconst clearData = () => {//用戶數據清空userInfo.value = {}//購物車清空cartStore.clearCart()}

在這里插入圖片描述

8. 合并購物車到服務器(重要)

目的是讓用戶在非登錄狀態下的行為有效,別白操作一頓

  • 登錄時調用合并購物車接口
//合并購物車    apis/cart.js
export const mergeCartAPI = (data) => {return httpInstance({url: '/member/cart/merge',method: 'post',data})
}
//stores/user.js
//合并購物車的操作 根據現有數組經過映射得到一個全新的數組使用mapmergeCartAPI(cartStore.cartList.map(item => {return {skuId: item.skuId,selected: item.selected,count: item.count}}))
  • 獲取最新的購物車列表

  • 覆蓋本地購物車列表

 cartStore.updateNewList()

如何測試?非登錄添加新商品,登錄看network的接口有沒有merge
在這里插入圖片描述


結算

1. 路由配置和基礎數據渲染

在這里插入圖片描述
在這里插入圖片描述

  • views/Cheakout/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>
  • 配置路由,引入組件配置二級路由
{path: 'checkout',component: Checkout
},
  • 給按鈕綁定事件,實現跳轉
 <el-button size="large" type="primary" @click="$router.push('/checkout')">下單結算</el-button>
  • 封裝接口apis/checkout.js
import httpInstance from "@/utils/http";//獲取結算信息
export const getCheckoutInfoAPI = () => {return httpInstance({url: '/member/order/pre'})
}
  • 獲取數據,渲染數據(默認地址、商品列表、統計數據)
<!-- 訂單頁 -->
<script setup>
import { getCheckoutInfoAPI } from '@/apis/checkout.js'
import { onMounted, ref } from 'vue'
const checkInfo = ref({})  // 訂單對象
const curAddress = ref({})  // 地址對象
const getCheckoutInfo = async () => {//獲取結算數據const res = await getCheckoutInfoAPI()console.log(res)checkInfo.value = res.result//適配默認地址,根據isDefault === 0篩選,使用filter或find篩選都可以const item = checkInfo.value.userAddresses.find(item => item.isDefault === 0)curAddress.value = item
}
onMounted(() => getCheckoutInfo())
</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>

在這里插入圖片描述

2. 地址切換-打開彈框交互實現

在這里插入圖片描述

  • 打開彈框,回顯用戶可選地址列表

彈框組件: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>

綁定數據showDialog,點擊按鈕控制彈框打開關閉,渲染可選地址列表

//控制彈框打開
const showDialog = ref(false)
...
<el-dialog title="切換收貨地址" width="30%" center v-model="showDialog">
...
...
<el-button size="large" @click="showDialog = true">切換地址</el-button>
...

在這里插入圖片描述

3. 切換地址-地址激活交互實現

在這里插入圖片描述

這個需求是通用類需求,學習以后可以多多的用

綁定事件,拿到地址這一項

 <div class="text item" @click="switchAddress(item)" v-for="item in checkInfo.userAddresses" :key="item.id">
//激活拿到這個對象
const activeAddress = ref({})
const switchAddress = (item) => {//將拿到的這個對象記錄下來activeAddress.value = item
}

激活樣式,判斷條件是激活對象id===當前項id

 :class="{ active: activeAddress.id === item.id }"

給確認按鈕綁定事件,新地址覆蓋原地址

 <el-button type="primary" @click="addressConfirm">確定</el-button>
//地址確認
const addressConfirm = () => {//覆蓋當前的地址curAddress.value = activeAddress.value//關閉彈層showDialog.value = false//當前地址置為初始值activeAddress.value = {}
}

在這里插入圖片描述

4. 生成訂單功能實現

購物車清空

在這里插入圖片描述

  • 準備 支付 路由 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>
  • 路由,二級
{path: 'pay',component: Pay
}
  • 接口封裝
// 創建訂單
export const createOrderAPI = (data) => {return httpInstance({url: '/member/order',method: 'POST',data})
}
  • checkout/index.vue引入,給 提交訂單 綁定事件,調用接口傳參,從res獲得id,使用orderId記錄,然后路由傳參。
<el-button type="primary" size="large" @click="createOrder">提交訂單</el-button>
// 創建訂單
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}})
}

在這里插入圖片描述

更新購物車


支付

1. 渲染基礎數據

在這里插入圖片描述

支付頁有倆個關鍵數據,一個是要支付的錢數,一個是倒計時數據(超時不支付商品釋放)

  • 獲取并調用訂單詳情的接口apis/pay.js
import httpInstance from '@/utils/http'export const getOrderAPI = (id) => {return httpInstance({url: `/member/order/${id}`})
}
<script setup>
import { getOrderAPI } from '@/apis/pay.js'
import { onMounted, ref } from 'vue'
const payInfo = ref({})  //支付信息
const getPayInfo = async () => {//獲取支付詳情const res = await getOrderAPI(route.query.id)payInfo.value = res.resultonMounted(() => getPayInfo())
}
</script>

2. 實現支付功能

在這里插入圖片描述

支付攜帶參數:放到Pay/index.vue中,綁定給按鈕即可

// 支付地址
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}`

綁定:

<!-- 微信 -->
<a class="btn wx" href="javascript:;"></a>
<!-- 支付寶 -->
<a class="btn alipay" :href="payUrl"></a>

在這里插入圖片描述

支付寶沙箱賬號信息:

賬號jfjbwb4477@sandbox.com
登錄密碼111111
支付密碼111111

應該是支付不了,但是正常跳轉沒問題

3. 支付結果展示

沒法支付了,這個模塊沒法驗證了,那我們來看看具體的寫法吧,以后應該會用到

在這里插入圖片描述

  • 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>
  • 路由配置,二級,path不是隨便寫的昂
{path: 'paycallback',component: PayBack
}
  • 根據支付結果payResult適配支付狀態
 <!-- 支付圖標 -->
<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>
<!--PayBack.vue--> 
<script setup>
import { getOrderAPI } from '@/apis/pay'
import { onMounted, ref } from 'vue'
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
}onMounted(() => getOrderInfo())
</script><p>支付金額:<span>¥{{ orderInfo.payMoney?.toFixed(2) }}</span></p>

4. 封裝倒計數函數

在這里插入圖片描述

編寫一個函數 useCountDown 可以把秒數格式化為倒計時的顯示狀態

formatTime為顯示的倒計時時間

start是倒計時啟動函數,調用時可以設置初始值并且開始倒計時

步驟

  • 編寫函數框架,確定參數和返回值
  • 編寫核心倒計時邏輯實現基礎倒計時
  • 實現格式化

裝一個dayjs插件:npm i dayjs

//comppsables/useCountDown.js
// 封裝倒計時邏輯函數
import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'export const useCountDown = () => {// 1. 響應式的數據let timer = nullconst time = ref(0)// 格式化時間 為 xx分xx秒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}
}
<!--Pay/index.vue-->
<script>
import { useCountDown } from '@/composables/useCountDown.js'
// 倒計時
const { start, formatTime } = useCountDown()// 獲取訂單數據
const route = useRoute()
const payInfo = ref({})
const getPayInfo = async () => {const res = await getOrderAPI(route.query.id)payInfo.value = res.result//初始化倒計數秒數start(res.result.countdown)
}
onMounted(() => getPayInfo())//跳轉支付
// 攜帶訂單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><p>支付還剩 <span>{{ formatTime }}</span>, 超時后將取消訂單</p>

在這里插入圖片描述

接口老是崩掉emmm


小結

功能有些雜,代碼書寫的位置要仔細斟酌以便后期維護。

看網絡請求的時候,要記得打開檢查左上角的錄制網絡日志不然不顯示(默認是開的),我不知道點哪了給關了,找這個bug找半天。
祝大家學習順利
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/18952.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/18952.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/18952.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

跨境人必讀:X(原Twitter)和Facebook區別是什么?

在今日全球化的商業環境中&#xff0c;跨境電商領域的企業和獨立站賣家正逐漸認識到社交媒體營銷的巨大潛力。特別是X&#xff08;原Twitter&#xff09;和Facebook&#xff0c;作為領先的社交媒體平臺&#xff0c;它們的使用不僅能夠提升品牌知名度&#xff0c;還能直接影響銷…

基于Java實現的圖書管理系統

前言&#xff1a;該圖書管理系統實現了查找、添加、刪除、顯示、借閱、歸還等功能&#xff0c;分為兩個用戶群體&#xff1a;管理者和普通用戶。使用了類與對象&#xff0c;封裝繼承多態&#xff0c;抽象類和接口等Java基礎知識。 一.思路 面向對象三部曲&#xff1a;找對象&…

oracle數據庫查看各類文件的位置

select name from v$controlfile; --控制文件 &#xff08;一般以.ctl結尾&#xff09; select file_name from dba_data_files; --數據文件 &#xff08;一般以.dbf或.ora結尾&#xff09; select file_name from dba_temp_files; --臨時文件&#xff08;一般以.d…

OrangePi_Kunpeng_Pro開發板測驗——性能巨人

文章目錄 &#x1f4d1;前言一、開箱初體驗的愉悅二、產品規格概述三、前置工作四、性能測試4.1 CPU 性能測試4.1.1 單線程 CPU 測試4.1.2 多線程 CPU 測試 4.2 內存性能測試4.2.1 內存讀寫性能測試4.2.2 高負載內存測試 4.3 I/O 性能測試4.4 網絡性能測試4.5 測試小結4.5.1 CP…

ECMAScript簡介

前言 ECMAScript&#xff08;通常簡稱為ES&#xff09;由ECMA國際標準化組織制定的一種腳本語言標準&#xff0c;Netscape最初開發的JavaScript演變而來。ECMAScript為JavaScript提供了基礎語言結構和功能。最初設計成一種腳本語言&#xff0c;用來服務Web。作為腳本語言ES同時…

CF1148C C. Crazy Diamond

題目鏈接 題意&#xff1a;給定一個數組p長度為n按照規則對下標滿足2 * abs(i - j) > n進行交換&#xff0c;最后使數組不遞減。輸出用的交換次數和每次交換的下標。&#xff08;交換次數不能超過5*n次&#xff09; 題解&#xff1a; 默認i < j,否則交換 abs(i - j) &…

基于異構圖的大規模微服務系統性能問題診斷

簡介&#xff1a;本文介紹由南開大學、清華大學、騰訊、國家超級計算天津中心共同合作的論文&#xff1a;基于異構圖的大規模微服務系統性能問題診斷。該論文已被IEEE Transactions on Services Computing期刊錄用 論文標題&#xff1a;Diagnosing Performance Issues for Lar…

docker刪除所有容器

筆記 要使用 Docker 刪除所有容器&#xff08;無論是停止的還是正在運行的&#xff09;&#xff0c;可以按照以下步驟操作&#xff1a; 1. **刪除所有正在運行的容器**&#xff1a; 首先&#xff0c;您需要停止所有正在運行的容器。可以使用以下命令&#xff1a; dock…

MATLAB分類與判別模型算法:K-近鄰法(KNN)分類代碼 【含Matlab源碼 MX_001期】

算法簡介&#xff1a; K-近鄰法&#xff08;KNN&#xff09;是一種簡單而有效的分類算法&#xff0c;也可用于回歸問題。它的基本原理是根據待分類樣本與訓練樣本的距離&#xff0c;選取最近的K個樣本進行投票決定分類。該算法無需訓練過程&#xff0c;而是利用訓練數據集直接…

數據結構與算法-反轉單鏈表

數據結構與算法-反轉單鏈表 大家好&#xff0c;歡迎回到我們的算法學習系列。今天&#xff0c;我們將探討一個在算法面試中非常經典的問題——反轉單鏈表。 什么是單鏈表&#xff1f; 在介紹問題之前&#xff0c;我們先簡單了解一下單鏈表。單鏈表是一種線性數據結構&#x…

氣缸前端鎖緊技術探討:從四個方面、五個方面、六個方面和七個方面深度解析

氣缸前端鎖緊技術探討&#xff1a;從四個方面、五個方面、六個方面和七個方面深度解析 在工業自動化領域&#xff0c;氣缸作為關鍵的執行元件&#xff0c;其前端鎖緊技術的穩定性與可靠性直接影響到整個系統的運行效率。本文將從四個方面、五個方面、六個方面和七個方面&#…

python 面對對象 類 補充

isinstance isinstance()&#xff1a;判斷一個實例化對象是否屬于這個類的&#xff0c;isinstance(對象&#xff0c;類) class Man():passclass Women():passa Man()print(isinstance(a, Man)) # True print(isinstance(a, Women)) # False 類的屬性操作 getattr() 獲…

小白windows系統從零開始本地部署大模型全記錄

大家好&#xff0c;最近兩年大語言模型風靡全球&#xff0c;最近&#xff0c;不少開源大模型&#xff0c;將模型部署到自己的電腦上&#xff0c;用個性化的數據微調想必是不少人的愿望&#xff0c;這次&#xff0c;讓我來分享從hugging face上下載部署chatglm3-6b中的經驗。 1.…

自動控制: 最小二乘估計(LSE)、加權最小二乘估計(WLS)和線性最小方差估計

自動控制&#xff1a; 最小二乘估計&#xff08;LSE&#xff09;、加權最小二乘估計&#xff08;WLS&#xff09;和線性最小方差估計 在數據分析和機器學習中&#xff0c;參數估計是一個關鍵步驟。最小二乘估計&#xff08;LSE&#xff09;、加權最小二乘估計&#xff08;WLS&…

conda環境里安裝ffmpeg

遇到的問題 在執行腳本的時候提示&#xff1a; /home/xxx/anaconda3/envs/llm-asr/lib/python3.9/site-packages/pydub/utils.py:170: RuntimeWarning: Couldnt find ffmpeg or avconv - defaulting to ffmpeg, but may not workwarn("Couldnt find ffmpeg or avconv - …

wifi貼碼推廣哪家靠譜?

如今越來越多的人想輕資產創業&#xff0c;WIFI貼碼是共享行業最無成本的創業項目了&#xff0c;而在選擇廠商的時候&#xff0c;大家就想要知道哪家公司靠譜&#xff0c;更好、更便宜、可靠。那么wifi貼碼推廣哪家靠譜&#xff1f;別急&#xff0c;下面小編將帶你一起了解。 目…

OpenAI開始訓練新的前沿模型——但GPT-5至少在90天內不會推出

ChatGPT 制造商 OpenAI 今早宣布&#xff0c;已開始訓練其新的“前沿模型”&#xff0c;并成立了一個新的安全委員會&#xff0c;由現任董事會成員 Bret Taylor&#xff08;OpenAI 董事會主席兼客戶服務初創公司 Sierra AI 聯合創始人、前谷歌地圖負責人和前 Facebook 首席技術…

BGP路由策略實驗

一、實驗拓撲 二、IP分配(骨干) R1&#xff1a; 0/0/0 15.0.0.1 24 0/0/1 18.0.0.2 24 0/0/2 19.0.0.1 24 R2: 0/0/0 16.0.0.1 24 0/0/1 15.0.0.2 24 R3: 0/0/0 17.0.0.2 24 0/0/1 18.0.0.1 24 R4: 0/0/0 16.0…

元宇宙vr工業產品展示空間降低研發成本

元宇宙產品虛擬展廳搭建編輯器為您提供了一個自助式元宇宙場景搭建的絕佳平臺。無論您是設計公司、攝影公司、營銷公司還是教育機構&#xff0c;我們都能為您量身打造專屬的元宇宙解決方案&#xff0c;滿足您的多樣化需求。 元宇宙產品虛擬展廳搭建編輯器具備強大的3D編輯功能&…

藍牙設備中的UUID

文章目錄 一、Device UUID二、Service UUID 一、Device UUID Device UUID也可以被稱作為DeviceID。 Android 設備上掃描獲取到的 deviceId 為外圍設備的 MAC 地址&#xff0c;相對固定。iOS 設備上掃描獲取到的 deviceId 是系統根據外圍設備 MAC 地址及發現設備的時間生成的 …