vue实现汇率转换
实现汇率转换功能
在Vue中实现汇率转换功能,可以按照以下步骤进行开发:
安装依赖 需要安装axios用于获取汇率API数据
npm install axios
创建Vue组件
<template>
<div class="currency-converter">
<h3>汇率转换器</h3>
<div class="input-group">
<input type="number" v-model="amount" placeholder="输入金额" />
<select v-model="fromCurrency">
<option v-for="currency in currencies" :key="currency" :value="currency">
{{ currency }}
</option>
</select>
<span>转换为</span>
<select v-model="toCurrency">
<option v-for="currency in currencies" :key="currency" :value="currency">
{{ currency }}
</option>
</select>
<button @click="convert">转换</button>
</div>
<div class="result" v-if="convertedAmount">
{{ amount }} {{ fromCurrency }} = {{ convertedAmount }} {{ toCurrency }}
</div>
</div>
</template>
组件逻辑
<script>
import axios from 'axios';
export default {
data() {
return {
amount: 0,
fromCurrency: 'USD',
toCurrency: 'CNY',
convertedAmount: 0,
currencies: ['USD', 'EUR', 'GBP', 'CNY', 'JPY'],
rates: {}
};
},
created() {
this.fetchExchangeRates();
},
methods: {
async fetchExchangeRates() {
try {
const response = await axios.get('https://api.exchangerate-api.com/v4/latest/USD');
this.rates = response.data.rates;
} catch (error) {
console.error('获取汇率失败:', error);
}
},
convert() {
if (!this.amount || isNaN(this.amount)) return;
const rate = this.rates[this.toCurrency] / this.rates[this.fromCurrency];
this.convertedAmount = (this.amount * rate).toFixed(2);
}
}
};
</script>
样式部分
<style scoped>
.currency-converter {
max-width: 500px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
.input-group {
display: flex;
gap: 10px;
align-items: center;
margin-bottom: 20px;
}
input, select, button {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #42b983;
color: white;
cursor: pointer;
}
.result {
font-size: 18px;
font-weight: bold;
}
</style>
使用免费汇率API
可以使用以下免费API获取实时汇率数据:
- ExchangeRate-API:
https://api.exchangerate-api.com/v4/latest/USD - Open Exchange Rates:
https://openexchangerates.org/api/latest.json - 中国银行外汇牌价API:
https://www.boc.cn/sourcedb/whpj/
实现自动更新汇率
可以添加定时器定期更新汇率数据:
data() {
return {
// 其他数据...
interval: null
}
},
created() {
this.fetchExchangeRates();
this.interval = setInterval(this.fetchExchangeRates, 3600000); // 每小时更新一次
},
beforeDestroy() {
clearInterval(this.interval);
}
添加货币符号显示
可以创建货币符号映射:
data() {
return {
currencySymbols: {
'USD': '$',
'EUR': '€',
'GBP': '£',
'CNY': '¥',
'JPY': '¥'
}
}
}
然后在模板中使用:
{{ currencySymbols[fromCurrency] }}{{ amount }} = {{ currencySymbols[toCurrency] }}{{ convertedAmount }}






