I’m trying to implement a convert() function in a Vue3 project.
I have a functions.js file to store some “global” basic functions
import axios from 'axios' let functions = {} functions.convert = async (amount, currencySetting) => { const result = await getRate(currencySetting) const rateData = result.data const rate = rateData[`EUR_${currencySetting}`] const converted = rate * amount return Math.round(converted) } function getRate(currency) { const apiKey = process.env.VUE_APP_CURRENCY_API_KEY return axios.get( `https://free.currconv.com/api/v7/convert?q=EUR_${currency}&compact=ultra&apiKey=${apiKey}` ) } export default functions
I’m calling the function inside a component like this
<script> import functions from '@/functions.js' export default { name: 'SltResult', props: { data: { type: Object, required: true } }, computed: { formattedIrp() { if (this.data.irp != 'n/a') { const currencySetting = this.$store.state.currency.currency if (currencySetting != 'EUR') { const convertedIrp = functions.convert(this.data.irp, currencySetting) return convertedIrp + currencySetting } else { return this.data.irp + '€' } } return this.data.irp } } } </script>
But it doesn’t work properly, I only get a pending Promise result… Can anybody tell me what I’m doing wrong? I’m learning Vue and JS….
Advertisement
Answer
There is two problems with your code.
- Logical issue. It doesn’t make sense to have ajax call inside a computed property, just use a normal method.
- Syntax issue. Your
convert
function is async, which means you need to wait for it to get the value.
This is a working version of your code:
<script> import functions from '@/functions.js' export default { name: 'SltResult', data: () => ({ formattedIrp: null, }), props: { data: { type: Object, required: true } }, mounted() { if (this.data.irp != 'n/a') { const currencySetting = this.$store.state.currency.currency if (currencySetting != 'EUR') { functions.convert(this.data.irp, currencySetting).then(result => { this.formattedIrp = result + currencySetting; }) } else { this.formattedIrp = this.data.irp + '€' } } this.formattedIrp = this.data.irp } } } </script>