Skip to content

button function to sum of two numbers using Vuejs

I’m trying to display the sum of two numbers using VueJs, but I want to develop this code so it would get the sum when the user clicks the button. please help me!

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
</head>
<body>
  
<div id="app">
            Enter number 1:<input type="number" name="number1" v-model="number1">
            <p></p>
            Enter number 2:<input type="number" name="number2" v-model="number2">
            <p></p>
            <hr>
            <p>TOTAL:{{ result }}</p>
</div>

<script>
  new Vue({
  el: '#app',
  data: {
    number1: 0,
    number2: 0,
  },
  computed: {
    result() {
        return parseInt(this.number1) + parseInt(this.number2);

    }
  }
});
</script>
</body>
</html>

Answer

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
</head>
<body>
  
<div id="app">
            Enter number 1:<input type="number" name="number1" v-model="number1">
            <p></p>
            Enter number 2:<input type="number" name="number2" v-model="number2">
            <p></p>
<button @click="add()">Sum</button>
            <hr>
            <p>TOTAL:{{ result }}</p>
</div>

<script>
  new Vue({
  el: '#app',
  data: {
    number1: 0,
    number2: 0,
    result:0
  },
  methods: {
    add() {
        this.result= parseInt(this.number1) + parseInt(this.number2);

    }
  }
});
</script>
</body>
</html>