DEV Community

Cover image for Understanding the Vue 3 Composition API
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

13 1 1

Understanding the Vue 3 Composition API

The Vue 3 Composition API introduces a powerful new way to structure and organize code, giving developers more flexibility and control. While the Options API remains a staple for many, the Composition API offers a modern approach that excels in scalability and reusability.

In this guide, we’ll break down the key concepts of the Composition API and show you how to use it effectively in your Vue 3 applications :)

Enjoy!

🤔 What is the Composition API and why you should try it?

The Composition API is a feature introduced in Vue 3 that enables developers to organize code by logical concerns rather than by component options like data, methods, and computed. It leverages functions and reactive primitives to encapsulate and reuse logic.

Using Composition API provides following advantages:

  1. Better Code Organization: Logic is grouped by functionality, not by options.
  2. Reusability: Easily extract and reuse logic across components using composables.
  3. Scalability: Simplifies managing large components by reducing clutter.
  4. TypeScript-Friendly: Works seamlessly with TypeScript, improving type safety.

The Composition API is ideal for large-scale projects, components with complex logic, or/and teams that want improved code reusability and readability.

🟢 Key concepts of the Composition API

The Composition API comes with few key concepts that you should be aware of to utilize its full potential.

1. Reactive State Management

ref creates a reactive reference for a single value. Access or modify the value using .value.

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Learn the difference between ref and reactive here.

2. Computed Properties

computed is used to create reactive, derived data based on other reactive values.

<script setup>
import { ref, computed } from 'vue';

const count = ref(0);

const double = computed(() => count.value * 2);
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double: {{ double }}</p>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

3. Watchers

watch observes reactive values and performs actions when they change.

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`);
});
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

4. Lifecycle Hooks

The Composition API offers equivalent lifecycle hooks as functions.

<script setup>
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  console.log('Component mounted');
});

onUnmounted(() => {
  console.log('Component unmounted');
});
</script>
Enter fullscreen mode Exit fullscreen mode

5. Composables

A composable is a reusable function that encapsulates logic. It’s a cornerstone of the Composition API’s reusability.

Example: Composable for Counter Logic

// 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 };
}
Enter fullscreen mode Exit fullscreen mode

Using the Composable:

<script setup>
import { useCounter } from './useCounter';

const { count, increment, decrement } = useCounter();
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Learn more about good practices and design patterns for Vue composables here

📖 Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

✅ Summary

The Vue 3 Composition API provides a modern, flexible way to handle state and logic, making your applications easier to scale and maintain. By understanding and using reactive primitives, computed properties, watchers, and composables, you can write cleaner and more reusable code.

Start experimenting with the Composition API today to unlock its full potential!

Take care and see you next time!

And happy coding as always 🖥️

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (3)

Collapse
 
firacode profile image
Firacode

The Vue 3 Composition API offers a modern way to organize and structure code by focusing on functionality rather than component options like data and methods. It enhances code organization, scalability, and reusability by using reactive primitives such as ref and computed, which manage state and derive values based on reactive data. Watchers allow developers to observe changes in state, while lifecycle hooks like onMounted and onUnmounted help manage component behavior. Additionally, composables—reusable functions that encapsulate logic—make it easier to share code across components. This approach is particularly beneficial for large-scale applications and teams looking for cleaner, more maintainable code, especially when working with TypeScript for improved type safety.

Collapse
 
bcostaaa01 profile image
Bruno

Great article Jakub! 👏 I agree with every point you mentioned.

It is so much better to build Vue solutions with the Composition API than with the old Options API! I didn’t like the way the script syntax was previously designed, because it felt like I was working with objects rather than actually JS logic. 😅 But now with the Composition API, everything is much easier, and cleaner, beside the fact that it is also easier to work with the template, too, since you know exactly where the logic and the properties are, rather than looking through nested objects. 🧽

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

Thanks Buddy, I like this syntax a lot too! :)

Happy coding!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay