Vue Methods
In Vue components, methods are functions defined within <script setup>. They are typically used to respond to events, perform calculations, or encapsulate reusable logic. These methods can be called by event handlers in templates or used in other logic within the component.
Defining Methods
In Vue 3's Composition API, we directly declare functions within the <script setup> block. These functions are automatically exposed for use in templates.
In this example:
- We defined a function named
greet. - This function can access the reactive variable
name. Note that when accessing variables created withrefin the<script>section, you need to use.value. - In the template, we use
@click="greet"to bind the button's click event to thegreetmethod. When the button is clicked, thegreetfunction will execute.
Methods with Parameters
Methods can accept parameters. You can pass static values or dynamic data when calling them.
Event Object
Sometimes, you need to access the native DOM event object. You can pass the special $event variable into a method:
If the event handler is an inline function (an arrow function), the event object will also be automatically passed:
Difference Between Methods and Regular Functions
In the context of the Composition API, the term "method" is more of a conceptual designation for functions created to respond to events or encapsulate specific behaviors. Technically, they are just regular JavaScript functions.
Unlike Vue 2's Options API, in the Composition API, you don't need to define methods in a specific methods object. You simply declare functions in <script setup>, and Vue will automatically handle the rest, making them available in templates.
This approach provides greater flexibility, allowing you to organize code based on logical functionality rather than being constrained by a fixed options structure.