运用vue框架实现人民币和各个币种之间汇率的换算
时间: 2023-11-14 07:04:07 浏览: 78
首先,需要引入vue和axios库。
html代码:
```
<div id="app">
<h1>汇率换算</h1>
<form>
<label>选择货币:</label>
<select v-model="fromCurrency">
<option v-for="(value, key) in exchangeRates" :value="key">{{ key }}</option>
</select>
<br><br>
<label>选择要转换成的货币:</label>
<select v-model="toCurrency">
<option v-for="(value, key) in exchangeRates" :value="key">{{ key }}</option>
</select>
<br><br>
<label>输入金额:</label>
<input type="number" v-model="amount">
<br><br>
<input type="button" value="换算" @click="convert">
</form>
<br>
<div v-if="result">{{ fromCurrency }}{{ amount }} = {{ toCurrency }}{{ result }}</div>
</div>
```
js代码:
```
new Vue({
el: '#app',
data: {
exchangeRates: {},
fromCurrency: '',
toCurrency: '',
amount: null,
result: null
},
mounted() {
axios.get('https://api.exchangeratesapi.io/latest?base=CNY')
.then(response => {
this.exchangeRates = response.data.rates
this.fromCurrency = 'CNY'
this.toCurrency = Object.keys(this.exchangeRates)[0]
})
.catch(error => console.log(error))
},
methods: {
convert() {
if (this.fromCurrency === this.toCurrency) {
this.result = this.amount
} else {
const fromRate = this.exchangeRates[this.fromCurrency]
const toRate = this.exchangeRates[this.toCurrency]
const result = (this.amount / fromRate) * toRate
this.result = result.toFixed(2)
}
}
}
})
```
代码中使用axios发送请求,获取汇率数据。mounted()方法中,通过调用API获取以人民币为基准的汇率数据,并将数据保存在exchangeRates对象中。同时将fromCurrency和toCurrency初始化为第一个货币名称。convert()方法中,根据用户选择的货币和输入的金额,计算出转换后的金额,并将结果保存在result变量中。最后,将结果展示在页面上。
阅读全文