<!-- 新增按鈕 -->
<div>
<button>綠界支付</button>
</div>
createApp({
data() {
return {
serverDomain: 'http://localhost:30000',
buyItem: {}, //{"1":8, "2": 5/"id":"amount"}
products: []
}
},
}).mount('#app');
serverDomain
:buyItem
:products
:<body>
<div id="app">
{{buyItem}}
</div>
</body>
<td>
<input v-model="buyItem[product.id]" type="number" min="0" max="100" step="1">
</td>
createApp({
data() {
return {
buyItem: {}, //{"1":8, "2": 5/"id":"amount"}
products: []
}
},
methods: {
getItemDetailByBuyItem() {
return Object.entries(this.buyItems).map(([id, amount]) => ({
productId: Number(id),
price: this.products.find(product => product.id === Number(id)).price,
amount: Number(amount)
})); //[{productId:1, price: 100, amount: 9}]
}
}
}).mount('#app');
getItemDetailByBuyItem
方法:Object.entries(this.buyItems)
:.map(([id, amount]) => ({...}))
:Number(id)
:this.products.find(product => product.id === Number(id)).price
:Number(amount)
:createApp({
data() {
return {
buyItem: {}, //{"1":8, "2": 5/"id":"amount"}
products: []
}
},
//打API
async sendPayment(url, date) {
try {
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
cors: 'no-cors',
body: JSON.stringify(data)
})
.then((res) => {
if (res.ok) return res.json();
return res.json().then((json) => Promise.reject(json));
});
return result;
} catch (e) {
console.error('~ file: index.js ~ line 32 ~ sendPayment ~ e', e)
throw new Error(e)
}
}
}
}).mount('#app');
async
):fetch
方法:處理回應:
.then((res) => { ... })
:處理 fetch
方法返回的 Promise。
try...catch
):async ECPay() {
//檢查 buyItems 是否為空
if (!Object.keys(this.buyItems).length) return alert('沒有選項')
// 處理 items 陣列中的每個產品詳細內容
const items = this.getItemDetailByBuyItem();
console.log('~ file: index.js ~ line 50 ~ ECPay ~ items', items);
//發送支付請求
const result = await this.sendPayment(`${this.serverDomain}/orders/create`),
{
paymentProvider: "ECPAY",
paymentWay: "CVS",
contents: items,
});
console.log(result);
}
}
async
):buyItems
是否為空:if (!Object.keys(this.buyItems).length) return alert('沒有選項');
const items = this.getItemDetailByBuyItem();
console.log('~ file: index.js ~ line 50 ~ ECPay ~ items', items);
getItemDetailByBuyItem
方法,將 buyItems
中的每個項目轉換為詳細的產品資訊物件,並將結果賦值給 items
變數。console.log
將 items
內容輸出到控制台以便檢查。const result = await this.sendPayment(`${this.serverDomain}/orders/create`, {
paymentProvider: "ECPAY",
paymentWay: "CVS",
contents: items,
});
console.log(result);
await
調用 sendPayment
方法,向 serverDomain/orders/create
發送一個支付請求。sendPayment
方法會向 ${this.serverDomain}/orders/create 這個 URL 發送一個 HTTP POST 請求,包括支付提供者(paymentProvider
)、支付方式(paymentWay
)和購物車內容(contents
)。result
變數,並輸出到控制台。<!-- 新增按鈕 -->
<div>
<button @click="ECPay">綠界支付</button>
</div>
@click="ECPay"
表示當按鈕被點擊時會觸發 ECPay
方法,包括檢查購物車項目、獲取購買項目詳細資訊並發送支付請求。@click
是 Vue.js 中的事件綁定語法,等同於 v-on:click
。它用來監聽按鈕的點擊事件,並在點擊時執行指定的方法。1.前端畫面:
2.MySQL - ORDERS畫面: