[Vuejs]-How can I build a simple calculator with Vue.js, using v-model and maybe v-if?

1👍

Hi anaisUx and welcome to SO.

You need to produce some kind of code example. What have you tried? What doesn’t work?

But to answer your question about v-if: v-if isn’t gonna help you with your problem. v-if is used in VueJS templates to indicate if the element should be rendered or not. What you are describing here is some kind of business logic, that you shouldn’t put in your templates but inside your compenent and then render the results in your template.

Without beeing too harsh it looks like you are very new to VueJS and programming in general, so I’m gonna guide you in the right direction.

  1. Create your VuuJS app: https://v2.vuejs.org/v2/guide/#Getting-Started

  2. Create your input (time spent) and bind it to a data-property: https://v2.vuejs.org/v2/guide/#Handling-User-Input

  3. Time saved is dependant on time spent, so computed property looks like something that might work: https://v2.vuejs.org/v2/guide/computed.html

  4. Write your business logic with simple if statements.

In other words:

  1. Create a data-property named timespent
  2. Create a input in your template and bind it to timespent
  3. Create a computed property called timesaved that uses timespent to calculate how much time the customer would save.
  4. Render timesaved in your template

Expected result: As soon as a customer types something in your input the VueJS app should render timesaved to the template. This should update automatically.

You can practice on codepen, jsfiddle, codesandbox.io/s/vue or any other similar site and post your code here to get some feedback.

Edit: Since you’ve made an effort and tried a little, here is a working example:

https://codepen.io/bergur/pen/WqPjNo

new Vue({
  el: '#app',
  data() {  
    return {
      hours: ''       
    }
  },
  computed: {
    save() {
      if (this.hours > 0 && this.hours < 20) {
        return 1
      }
      if (this.hours >= 20 && this.hours < 30) {
        return 10
      }
      
      if (this.hours >= 30 && this.hours < 50) {
        return 20
      }            
      
      if (this.hours >= 50) {
        return 30
      }            
    }
  }
})

Data property hours stores how many hours the customer is spending on invoicing. Like i mentioned above there is no need for multiple v-if, the business logic should stay in the component.

I used a computed property save wjich stores the hours the custumer can save.

Leave a comment