In Vue, methods are functions defined within a Vue component that can be called to perform specific tasks or handle actions triggered by user interactions or other events.
Methods are typically defined in the methods option of a Vue component and can be invoked within the template or other methods of the component.
Methods are defined as functions within the "methods" object of a Vue component.
Each method is a key-value pair, where the key is the method name and the value is the function definition.
<script> export default { name: "App", data() { return { count: 0, }; }, methods: { increment() { this.count++; }, decrement() { this.count--; }, }, }; </script>
<template> <button @click="increment"> Increment </button> <span>Count: {{ count }}</span> <button @click="decrement"> Decrement </button> </template>
Methods can be called directly within the template using interpolation or event-handling directives such as "v-on".
the "increment" and "decrement" methods are called when the corresponding buttons are clicked.
message: "Great!!", }; }, methods: { increment() { if (this.count < 5) { this.count++; if (this.count === 5) { alert(this.message); } } }, decrement() { this.count--; }, }, }; </script>
Inside a method, we can access component data properties and other methods using the "this" keyword.
// App.vue <template> <button @click="increment"> Increment </button> <span>Count: {{ count }}</span> <button @click="decrement"> Decrement </button> <div> <button @click="greet('William')"> Greet </button> </div> </template> <script> export default { name: "App", data() { return { count: 0, message: "Great!!", }; }, methods: { increment() { if (this.count < 5) { this.count++; if (this.count === 5) { alert(this.message); } } }, decrement() { this.count--; }, greet(employeeName) { alert("Hi, " + employeeName); }, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Here, the "Great!!" will display in an alert when the count reaches to 5 and the "increment" method accesses the "message" data property of the component using "this.message".
Methods can accept parameters, which can be passed directly from the template.
the "greet" method accepts an "employeeName" parameter, which is passed when the button is clicked.
Methods in Vue provide a way to encapsulate logic and functionality within components, making it easier to manage and organize code.
They are commonly used for handling user interactions, performing calculations, making API calls, and other tasks within Vue components.