Vue.js Methods – Handling Logic and Events

Methods in Vue.js are functions defined inside a component to perform actions, respond to events, or manipulate reactive data. They are one of the core ways to add interactivity to your components.

1. Simple Method Example

Define a method inside the component and trigger it with a button click:

2. Counter Example

Incrementing a counter using a method:

3. Methods with Arguments

Pass arguments to methods directly from the template:

4. Todo List Example

Methods are used for adding and removing todos:

5. Methods vs Computed

Methods run every time they are called. Computed properties are cached based on dependencies:

6. Async Method Example

Fetch data asynchronously using a method:

7. Form Handling Example

Use methods to validate and submit forms:

8. Tips for Using Methods

  • Use methods for actions triggered by events.
  • Keep methods short and focused.
  • Use computed properties for derived values.
  • Emit events to communicate with parent components.
  • Async methods are great for fetching data.

Conclusion

Methods are a core part of Vue.js interactivity. By defining functions in your components, you can handle user events, manage state, interact with APIs, and communicate between components. With the updated VueCompiler, all method examples now work flawlessly in Next.js, allowing interactive, live tutorials for learning Vue.js effectively.