用Promise.all完成即時的當日漲跌幅及活躍股票排名看板
<template>
<NuxtLayout name="header">
<template #main>
// ...略
<div v-if="presenceStock" class="flex justify-around mb-5">
<ul>
<li>
<h3 class="text-center font-bold text-xl">當日上漲股票排名</h3>
</li>
<li v-for="(v,i) in gainRankingOnTheDay" class="presence shadow-xl mb-6">
<h4 class="text-xs text-center ">{{v.name}}</h4>
<div class="flex items-end justify-center mt-3 text-[#56a556]">
<p class="text-3xl font-bold me-1">{{v.price}}</p>
<p class="text-[#56a556] font-thin">{{ `+${v.changesPercentage}%` }}</p>
</div>
</li>
</ul>
<ul>
<li>
<h3 class="text-center font-bold text-xl">當日下跌股票排名</h3>
</li>
<li v-for="(v,i) in loseRankingOnThatDay" class="presence shadow-xl mb-6">
<h4 class="text-xs text-center ">{{v.name}}</h4>
<div class="flex items-end justify-center mt-3 text-[#ff0000]">
<p class="text-3xl font-bold me-1">{{v.price}}</p>
<p class="text-[#ff0000] font-thin">{{ `${v.changesPercentage}%` }}</p>
</div>
</li>
</ul>
<ul>
<li>
<h3 class="text-center font-bold text-xl">當日活躍股票排名</h3>
</li>
<li v-for="(v,i) in activeRankingOnThatDay" class="presence shadow-xl mb-6">
<h4 class="text-xs text-center ">{{v.name}}</h4>
<div class="flex items-end justify-center mt-3 text-zinc-700">
<p class="text-3xl font-bold me-1">{{v.price}}</p>
<p class="font-thin">{{ `${v.changesPercentage}%` }}</p>
</div>
</li>
</ul>
</div>
// ...略
</template>
</NuxtLayout>
</template>
<script setup>
// 排名資料集合
const presenceStock = ref()
// API
const gainersStockApi = `https://financialmodelingprep.com/api/v3/stock_market/gainers?apikey=XX`
const losersStockApi = `https://financialmodelingprep.com/api/v3/stock_market/losers?apikey=XX`
const activesStockApi = `https://financialmodelingprep.com/api/v3/stock_market/actives?apikey=XX`
const getData = (stock = 'AAPL') => {
// ...略
Promise.all([axios.get(gainersStockApi),axios.get(losersStockApi),axios.get(activesStockApi)])
.then((res)=>{
presenceStock.value=res
})
.catch((err)=>{console.log(err)})
// ...略
}
onMounted(() => {
getData()
})
// 漲幅前5
const gainRankingOnTheDay = computed(()=>{
const gainers = presenceStock.value?presenceStock.value[0].data:[]
console.log(gainers)
gainers.length = 5
return gainers
})
// 跌幅前5
const loseRankingOnThatDay = computed(()=>{
const losers = presenceStock.value?presenceStock.value[1].data:[]
losers.length = 5
return losers
})
//活躍前5
const activeRankingOnThatDay = computed(()=>{
const actives = presenceStock.value?presenceStock.value[2].data:[]
actives.length = 5
return actives
})
</script>
總共有3支API(上漲,下跌,活躍)
會把它們塞到一個變數是因為需要讓它們同時出現
用Promise.all去完成
然後在分別用computed去拆成3個變數(上漲前5,下跌前5,活躍前5)
之後再用v-for跑迴圈即大功告成!
小結:
今天進度緩慢...
加班就算了
APIKEY的環境變數突然壞掉不能用!?
只能先寫字串塞回去每個key
結果僅完成預計的1/2
挑戰不僅來自作品本身
還有與生活的平衡,時間的拿捏
明天要把進度追上!!