How to Use Vue Composition API for SPAs

How to Use Vue Composition API for SPAs

The Vue Composition API is a powerful feature introduced in Vue 3 that allows developers to organize their code in a more flexible and reusable way, especially when building Single Page Applications (SPAs). This article will guide you on how to effectively use the Vue Composition API for your SPAs.

Understanding the Vue Composition API

The Vue Composition API provides an alternative to the Options API, allowing developers to encapsulate their logic in reusable functions called “composables.” This approach enhances code readability and maintainability, enabling effective sharing of reactive state and logic across components.

Setting Up Your Vue Project

Before diving into the Composition API, ensure that your Vue project is set up. You can create a new Vue 3 project using Vue CLI:

vue create my-vue-spa

Once your project is created, navigate to the project folder:

cd my-vue-spa

Creating a Composable

To leverage the Composition API, start by creating a composable. Composables are JavaScript functions that use the reactive features of Vue. Create a new file in your project under `src/composables` folder (create the folder if it doesn't exist) and name it `useCounter.js`:


import { ref } from 'vue';
export function useCounter() {
  const count = ref(0);
  
  const increment = () => {
    count.value++;
  };
  
  const decrement = () => {
    count.value--;
  };
return { count, increment, decrement };
}

Using Your Composable in a Component

Next, you will integrate the `useCounter` composable into a component. Open `src/components/Counter.vue` and use the Composition API:




This component reflects the count and provides buttons to increment and decrement the value using the functions defined in your composable.

Organizing Logic with Multiple Composables

In larger SPAs, you may find yourself writing multiple composables. Organize them sensibly based on functionality. For example, if you require API calls, create another composable like `useFetch.js` to handle API requests, separating concerns and enhancing reusability.


import { ref } from 'vue';
export function useFetch(url) {
  const data = ref(null);
  const error = ref(null);
const fetchData = async () => {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error('Network response was not ok');
      data.value = await response.json();
    } catch (err) {
      error.value = err.message;
    }
  };
return { data, error, fetchData };
}

Using Async Setup with Composables

Sometimes your composables might require asynchronous operations. You can combine the use of async functions within the `setup` method. Here’s how you can fetch data from an API when the component mounts:




Benefits of Using the Composition API for SPAs

  • Enhanced Code Clarity: With composables, related logic is grouped together, making your code cleaner and easier to understand.
  • Reusability: Code can be reused across multiple components, reducing duplication and simplifying maintenance.
  • TypeScript Compatibility: The Composition API is more