0

I'm trying to make a simple converter, that is, the user inputs the amount and the price gets converted. Suppose I have an input field on my website:

<input type="number" v-model="coin_amount" id="usd" placeholder="Amount (USD)">

And convert() function that converts coin_amount to another currency

convert() {
  axios({
    method: "GET",
    "url": "https://api.coinmarketcap.com/v1/ticker/" + this.input.cryptocurrency + "/"
  }).then(result => {
    this.coin_amount = this.coin_amount / result.data[0].price_usd;
  }, error => {
    console.error(error);
  });
  return this.coin_amount;
}

And i display the converted value like this:

<span><strong>Value:</strong> {{ coin_amount }}</span>

How can I invoke the convert() function so that it can convert the amount while typing (LIVE). I thought to use v-model but it just shows the inputted amount, not the converted one. I also thought to use a special convert button and invoke it with v-on:click="convert() but I want to make it more advanced.

1 Answer 1

2

Computed

It would be easiest to use a computed instead of a convert method:

computed: {
  converted() {
    // do stuff with `this.coin_amount` 
    // return the converted value
  }
}

Then in your template, show that computed property:

<span><strong>Value:</strong>{{ converted }}</span>

EDIT FOR ASYNC:

But now you've edited your question to show your converting code, and it's async.

Option 1

Since computeds are sync only, to continue using it async, you would need a solution like vue-async-computed. I would use the next option instead but here is what your code would look like using that package with your converting code:

asyncComputed: {
  async converted() {
    const result = await axios({ method: "GET", url: "https://api.coinmarketcap.com/v1/ticker/" + this.input.cryptocurrency + "/" });
    return this.coin_amount / result.data[0].price_usd;
  }
}

Option 2

Or you could use a watch, which are allowed to be async. In this example, converted is a data variable set by the watch, not a computed:

data() {
  coin_amount: null,
  converted: null,
  // ...   
},
watch: {
  async coin_amount(val) {
    const result = await axios({ method: "GET", url: "https://api.coinmarketcap.com/v1/ticker/" + this.input.cryptocurrency + "/" });
    this.converted = this.coin_amount / result.data[0].price_usd;
  }
}   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.