Vue.js 3 introduces the Composition API, offering a new way to structure and write your code. However, for those coming from Vue 2, the Options API remains available.
This article explores how to work with functions and methods in Vue 3 using both approaches and highlights their differences.
Writing Functions in Vue 3
Functions are reusable blocks of code that return a value or perform an operation. In Vue 3, you can define functions using traditional JavaScript syntax or the modern ES6 arrow functions.
Example: Using a Function with the Composition API
Here’s a simple example of defining and using a function in Vue 3:
setup() {
  const message = () => {
      return 'Hello Vue 3';
  };

  return {
      message,
  };
}
This function message is defined within the setup() function, a cornerstone of the Composition API. To use this function in your template:
<p>Message: {{ message() }}</p>
It’s important to call the function (using ()), as failing to do so will print the function itself rather than its result.
Methods in Vue 3
Vue 3 also supports methods, which are defined outside the setup() function. These methods belong to the Options API, a legacy approach from Vue 2.
Example: Defining Methods with the Options API
Here’s how you define a method:
methods: {
  countUsers() {
      return 10;
  }
}
To use this method in your template:
<p>Users: {{ countUsers() }}</p>
Combining Composition API and Options API
Vue 3 allows you to combine the Composition API and the Options API in the same component. However, features specific to the Composition API cannot be used within the Options API, and vice versa.
In the following example, the message function uses the Composition API, while countUsers uses the Options API:
const app = Vue.createApp({
  setup() {
      const message = () => {
          return 'Hello Vue 3';
      };

          return {
              message,
          };
      },
      methods: {
          countUsers() {
              return 10;
          }
      }
  });
Example Output
When mounted to a DOM element, the application renders:
<div id="app">
  <p>Message: Hello Vue 3</p>
  <p>Users: 10</p>
</div>
Key Differences Between Functions and Methods
Why Choose the Composition API?
While both APIs can coexist, the Composition API is generally preferred in Vue 3 because:
• It enables better organization of related logic within a single function
• It simplifies complex components by modularizing logic into composable functions
• It is the future-forward approach, offering greater flexibility and integration with Vue 3’s new features
Conclusion
Vue 3 provides developers with two distinct approaches: the Composition API for modern, modular development, and the Options API for backward compatibility and simplicity.
As Vue 3 evolves, the Composition API will likely become the standard for most projects, but the Options API remains a valuable tool for maintaining existing applications.