margherita pizza
margherita pizza

Reputation: 7165

how to apply watchers and computed properties for a complex calculation

My use case is something like this,

User can input Working hours and expenses,

based on these values, I have to do a calculation to get a final value,

and vat and payrate are pre-defined constants.

pay_amount = hours * payrate

tax_amount = pay_amount * vat/100

total = pay_amount + tax_amount +( expenses + (expenses * vat/100) )

This is my code. But it is not functioning as expects.

<template>
  <v-app>
    <v-container>
      <v-layout>
        <v-flex>
          <v-text-field
          label="Hours"
          v-model="hours">
          </v-text-field>

          <v-text-field
          label="expences"
          v-model="expences">
          </v-text-field>

          <h1>Pay amount = {{hours}} * {{payrate}} = {{pay_amount}}</h1>
          <h1>Vat amount = {{pay_amount}} * {{vat}} = {{vat_amount}}</h1>
          <h1>{{total}}</h1>
        </v-flex>
      </v-layout>
    </v-container>



  </v-app>
</template>

<script>
export default {
  computed: {
    pay_amount() {
      return this.hours * this.payrate;
    },
    vat_amount() {
      return this.pay_amount * this.vat / 100;
    },
    total() {
      return (
        this.vat_amount +
        this.pay_amount +
        this.expences * this.vat / 100 +
        this.expences
      );
    }
  },
  name: "App",
  data() {
    return {
      hours: "",
      payrate: 166,
      vat: 5,
      expences: "",
      expences_cal: ""
    };
  }
};
</script>

What's wrong with my code?

Upvotes: 1

Views: 171

Answers (1)

Ricky Ruiz
Ricky Ruiz

Reputation: 26781

Your data properties should have a starting value of 0 instead of a string empty since you are using numbers for calculations.

Also, you can take advantage of the v-model number modifier which automatically typecasts the value as a number.

Ex. v-model.number="yourDataProp"

Upvotes: 1

Related Questions