Home > front end >  button function to sum of two numbers using Vuejs
button function to sum of two numbers using Vuejs

Time:01-01

I try to display the sum of two numbers using VueJs but I want develop this code to get 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>

CodePudding user response:

You can add a "Calculate" button and use v-on directive to listen to click event:

<!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>
    <button v-on:click="result = parseInt(number1)   parseInt(number2)">Calculate</button>
    <p>TOTAL:{{ result }}</p>
</div>

<script>
new Vue({
    el: '#app',
    data: {
        number1: 0,
        number2: 0,
        result: null,
    },
});
</script>
</body>
</html>

CodePudding user response:

<!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>

  • Related