show me how to use vue.js to create an app that adds two numbers and show the result
- User
show me how to use vue.js to create an app that adds two numbers and show the result
- Assistant
show me how to use vue.js to create an app that adds two numbers and show the result
To create a simple Vue.js application that adds two numbers and displays the result, follow these steps:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Two Numbers</title>
<!-- Include Vue from the CDN for simplicity -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!-- Create two inputs for the numbers and bind them to the Vue instance data -->
<input type="number" v-model.number="number1">
<input type="number" v-model.number="number2">
<!-- A button to trigger the addition -->
<button @click="addNumbers">Add Numbers</button>
<!-- Display the result -->
<p>Result: {{ result }}</p>
</div>
<script>
// Vue application code will go here
</script>
</body>
</html>
script tag, create a new Vue instance and define the data and methods:<script>
new Vue({
el: '#app',
data: {
number1: 0,
number2: 0,
result: 0
},
methods: {
addNumbers: function() {
// Change the strings to numbers and add them
this.result = this.number1 + this.number2;
}
}
});
</script>
Now you have a fully functional app that can add two numbers. The v-model.number directive on the input tags takes care of binding the input values to the Vue instance data properties and also ensures they are cast to numbers (not strings). The .number modifier ensures that the user input is automatically typecast to a number.
The addNumbers method is called when the button is clicked (because of the @click directive), adding number1 and number2 together and storing the result in the result data property, which is then displayed in the <p> tag.
Here's the complete example for clarity:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Two Numbers</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="number" v-model.number="number1">
<input type="number" v-model.number="number2">
<button @click="addNumbers">Add Numbers</button>
<p>Result: {{ result }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
number1: 0,
number2: 0,
result: 0
},
methods: {
addNumbers: function() {
this.result = this.number1 + this.number2;
}
}
});
</script>
</body>
</html>
Just include this HTML in your web application, and you will have a working Vue.js app that adds two numbers.