不同金融市場的新聞篩選
// index.vue
<div class="flex w-[95%] mx-auto">
<div class="w-[20%] h-[500px] p-5 border border-solid border-black rounded box-border mt-2">
<div v-for="(v, name) in items" :key="v">
<input type="checkbox" :value="name" v-model="checkedNews" />
<label class="font-bold m-2 py-2">{{ v }}</label>
</div>
<button @click="chooseNews" class="bg-[#4f46e5] py-1 px-2 mt-3 rounded text-white font-bold">新聞篩選</button>
</div>
<div v-if="news !== undefined" class="flex flex-wrap justify-around w-[80%]">
<a
:href="v.url"
v-for="(v, i) in news"
class="inline-block box-border p-5 w-[300px] border border-solid border-black rounded shadow-2xl flex flex-col justify-around my-2"
>
<img :src="v.banner_image" alt="" />
<div>
<h3 class="py-1">{{ v.title }}</h3>
<p v-for="author in v.authors" class="text-xs">
{{ author }}
</p>
</div>
</a>
</div>
<div v-else class="w-[80%] text-center text-2xl mt-[200px]">
<h3>交叉比對無資料,請重新搜尋..</h3>
</div>
</div>
<script setup>
// 新聞資料
const news = ref()
const checkedNews = ref(['financial_markets']) //選中的新聞
const checkedNewsString = computed(() => checkedNews.value.join(','))
const items = ref({
blockchain: '區塊鏈',
earnings: '收益',
ipo: 'IPO',
mergers_and_acquisitions: '併購',
financial_markets: '金融市場',
economy_fiscal: '財政政策(稅改、政府支出)',
economy_monetary: '貨幣政策(利率、通貨膨脹)',
economy_macro: '總體經濟',
energy_transportation: '能源與運輸',
finance: '金融',
life_sciences: '生命科學',
manufacturing: '製造業',
real_estate: '房地產與',
retail_wholesale: '零售批發',
technology: '科技',
})
watchEffect(() => {
news.value
? news.value.forEach((v) => {
v.authors.reverse()
})
: []
})
const newsApi = computed(
() =>
`https://www.alphavantage.co/query?function=NEWS_SENTIMENT&topics=${checkedNewsString.value}&apikey=${alpha}`
)
const getData = (stock = 'AAPL') => {
// ...略
.then((res) => {
// ...略
return axios.get(newsApi.value)
})
.then((res) => {
news.value = res.data.feed
news.value.length = 20
})
.catch((err) => {
console.log(err)
})
}
getData()
// 選擇新聞類型
const chooseNews = () => {
console.log()
axios
.get(newsApi.value)
.then((res) => {
news.value = res.data.feed.length !== 0 ? res.data.feed : undefined
})
.catch((err) => {
console.log(err)
})
if (news.value !== undefined) news.value.length = 20
}
</script>
用V-if
建立checkbox
items是對應到label名稱跟value
選中的值是取交集去篩選新聞
然後透過computed
把array轉成字串後去打API取得資料
小結:
終於撐到連假!!
有時間可以研究一些比較麻煩有挑戰的項目了
希望各位看倌再給點耐心囉