```javascript
<template>
<div class="view-div">
<h2>货币汇率换算</h2><br />
<table class="contain-div">
<tr>
<td><input type="text" v-model="inputJPY"></td>
<td>日元JPY</td><br />
</tr>
<tr>
<td><span>人民币:{{ receCNY }}</span></td><br/>
</tr>
<tr>
<td><input type="text" v-model="inputCNY"></td>
<td>人民币CNY</td><br/>
</tr>
<tr>
<td><span>日元:{{ receJPY }}</span></td><br/>
</tr>
</table>
<br />
</div>
</template>
<script>
const API_KEY = "9e486aaedc2f40f5b8b8bee5aa55fd0b";
const API_URL = `https://openexchangerates.org/api/latest.json?app_id=${API_KEY}`;
export default {
name: 'CurrencyListTwo',
data() {
return {
inputJPY: 100,
inputCNY: 100,
receJPY: 0,
receCNY: 0,
}
},
methods: {
async convertCurrency(amount, fromCurrency, toCurrency) {
const response = await fetch(API_URL);
const exchangeRates = await response.json();
const convertedAmount = amount * exchangeRates.rates[toCurrency] / exchangeRates.rates[fromCurrency];
return convertedAmount;
}
},
watch: {
inputJPY: {
handler() {
this.convertCurrency(
this.inputJPY,
"JPY",
"CNY"
).then((result) => { this.receCNY = result.toFixed(2) })
},
immediate: true
},
inputCNY: {
handler() {
this.convertCurrency(
this.inputCNY,
"CNY",
"JPY"
).then((result) => { this.receJPY = result.toFixed(2) })
},
immediate: true
},
}
}
</script>
<style scoped>
.iew-div {
margin: auto;
padding: 20px 20px;
text-align: center;
}
.contain-div {
margin: auto;
}
</style>
## 用watch写一个实时汇率换算的小功能(基于vue2)
主要考察watch监视属性