2

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>

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.