[Vuejs]-Vue – using method/s to add together two inputs and save into data

0πŸ‘

βœ…

As requested. All you have to do is create 2 inputs and link them to a date, and calculate them according to the code below.

<div id="app">
<input v-model.number="value1" type="number"/>
<button v-on:click="val1">Save Amount</button>
<input v-model.number="value2" type="number"/>
<button v-on:click="val2">Save Amount</button>
<button @click="valueTotal">Total</button>
Total: {{total}}
</div>


new Vue({
el: '#app',
methods: {
val1 () {
    this.totalBox1 = this.value1
},
val2 () {
    this.totalBox2 = this.value2
},
valueTotal () {
    this.total = this.totalBox1 + this.totalBox2
}
},
data: {
totalBox1: '',
totalBox2: '',
value1: 0,
value2: 0,
total: ''
}
})

Example:
https://jsfiddle.net/hamiltongabriel/ke8w9czy/

0πŸ‘

No need for methods:

<template>
<div>
  <input type="text" v-model="item1"><br>
  <input type="text" v-model="item2">
  <p>Total</p>
  {{ total }}
</div>
</template>

<script>
export default {
  name: "Calculate",
  data() {
    return {
      item1: 0,
      item2: 0
    }
  },
  computed: {
    total () {
      return this.item1 + this.item2
    }
  }
}
</scrip>

0πŸ‘

here is how to it step by step with buttons, I showcased two way of calculating the total: with and without a method

<template>
  <div>

    <input type="text" v-model="input1">
    <input type="text" v-model="input2">

    <button @click="value1 = input1">save value 1</button>
    <button @click="value2 = input2">save value 2</button>

    <button @click="calculateTotal()">calculate total</button>
    <button @click="total = value1 + value2">calculate total</button>

    total : {{ total }}

  </div>
</template>

<script>
export default {
  name: "Calculate",
  data() {
    return {
      input1: 0,
      input2: 0,
      value1: 0,
      value2: 0,
      total: 0,
    };
  },
  methods:{
    calculateTotal(){
      this.total = this.input1 + this.input2;
    }
  }
};
</script>

you probably don’t want all the intermediate button click, so you could do it using directly the value bounded to the inputs:

<template>
  <div>

    <input type="text" v-model="value1">
    <input type="text" v-model="value2">

    <button @click="total = value1 + value2">calculate total</button>

    total : {{ total }}

  </div>
</template>

<script>
export default {
  name: "Calculate",
  data() {
    return {
      value1: 0,
      value2: 0,
      total: 0,
    };
  }
};
</script>

Leave a comment