Vue组件渲染后如何查询旧数据判断加密货币价格涨跌
实现步骤
1. 改造App.vue 存储每个代币的历史价格
你原来存的lastPrice是单个值,无法对应多个代币,需要改为按代币id存储历史价格的对象,同时给每个代币新增涨跌标记字段:
<template> <div id="app"> <div class="container mx-auto"> <div class="pt-6"> <h1 class="text-2xl font-bold">Crypto Monkey Cap</h1> <div v-for="token in listTokens" :key="token.id"> <div class="py-6"> <token-component :name="token.name" :price="token.current_price" :mcap="token.market_cap" :change-type="token.priceChange" ></token-component> </div> </div> </div> </div> </div> </template> <script> import TokenComponent from "./components/tokenComponent.vue"; export default { name: "App", components: { TokenComponent, }, data() { return { listTokens: [], lastPrices: {} // 替换原来的单个lastPrice,按代币id存储对应上次价格 }; }, mounted() { this.getTokens(); setInterval(() => { this.getTokens() }, 30000); }, methods: { getTokens() { fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd") .then((response) => response.json()) .then((data) => { // 遍历新数据,给每个代币计算涨跌标记 const processedData = data.map(token => { // 首次拉取无历史价格,标记为0(无变化) let changeType = 0 if (this.lastPrices[token.id] !== undefined) { // 1=上涨,-1=下跌,0=价格无变动 changeType = token.current_price > this.lastPrices[token.id] ? 1 : (token.current_price < this.lastPrices[token.id] ? -1 : 0) } // 更新历史价格存储 this.lastPrices[token.id] = token.current_price return { ...token, priceChange: changeType } }) this.listTokens = processedData; }); } } }; </script>
2. 改造tokenComponent 接收涨跌标记并绑定样式
子组件新增接收涨跌属性,给价格绑定动态类即可实现颜色区分:
<template> <div class="py-4 border-2 rounded-lg"> <div class="flex justify-around"> <h2>{{ name }}</h2> <!-- 绑定动态样式,涨为绿色,跌为红色,不变用默认颜色 --> <h2 :class="{ 'text-green-500': changeType === 1, 'text-red-500': changeType === -1 }">{{ price }} $</h2> <h2>{{ mcap }} $</h2> </div> </div> </template> <script> export default { props: { name: { required: true }, price: { required: true }, mcap: { required: true }, // 新增涨跌属性 changeType: { type: Number, default: 0 } } }; </script>
额外说明
- 首次拉取数据时没有历史价格对比,价格不会有特殊样式,第二次及之后拉取就会自动显示涨跌颜色
- 如果需要展示具体涨跌幅度,可以自行计算
(当前价格-上次价格)/上次价格*100后传给子组件展示
内容的提问来源于stack exchange,提问作者Jo Le Belge
相关产品推荐
相关产品推荐

