Web Development

Vue.js 3 Composition API Deep Dive

Understanding and implementing Vue 3's Composition API

A
admin

December 04, 2024

10 min read 5 tags
Vue.js 3 Composition API Deep Dive
Illustration 1 for Vue.js 3 Composition API Deep Dive

Illustration 1 for Vue.js 3 Composition API Deep Dive

Illustration 2 for Vue.js 3 Composition API Deep Dive

Illustration 2 for Vue.js 3 Composition API Deep Dive

Vue.js 3 Composition API: A Deep Dive

Vue.js has been one of the most popular JavaScript frameworks for building modern web applications. Since the release of Vue 3, the framework introduced a revolutionary new feature: the Composition API. This new API fundamentally changes how we build and organize Vue components, offering greater flexibility and better code organization.

In this article, we’ll dive deep into Vue 3’s Composition API, explore its benefits over the traditional Options API, and demonstrate how to effectively use it to build scalable and maintainable applications.

What is the Composition API?

The Composition API is a set of functions that allow you to better organize and reuse logic inside your Vue components. It provides a more flexible and modular approach compared to the traditional Options API, which uses properties like data, methods, computed, and watchers to organize logic in Vue components.

With the Composition API, you can group related logic together, making your code easier to maintain and scale. It also improves the reusability of your code across components.

The main goal of the Composition API is to improve the developer experience by offering better support for logic reuse, code organization, and type inference.

Why Should You Use the Composition API?

Here are the key reasons to consider using the Composition API:

  1. Better Logic Reuse: With the Composition API, logic can be grouped into reusable "composables," which are functions that encapsulate specific pieces of functionality. This is especially helpful in large projects where you need to share logic across multiple components.
  2. Improved Code Organization: In large components, the Options API often leads to scattered logic, which can make the code harder to follow. The Composition API allows you to group related logic together, leading to more organized and maintainable code.
  3. Easier TypeScript Support: Vue 3's Composition API is fully TypeScript-friendly. You get better support for type inference, making it easier to build type-safe applications.
  4. Better Reactivity Model: The Composition API provides a more flexible and intuitive reactivity system by using the ref() and reactive() functions, allowing for finer control over state and reactivity.

Basic Concepts of the Composition API

Before we dive into examples, let's look at some of the key concepts in the Composition API.

1. setup() Function

The setup() function is the entry point for the Composition API in Vue 3. It is called before the component is created and is the place to define the component's reactive state, computed properties, methods, and lifecycle hooks.

javascript

Copy code
<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}
</script>
  • setup() is executed only once when the component is created.
  • It can return values (e.g., data, methods, computed properties) that will be accessible in the component's template.
  • Reactive state in setup() is created using ref() or reactive().

2. ref() and reactive()

Both ref() and reactive() are used to create reactive state in Vue 3.

  • ref() is used to create a reactive reference to a primitive value (like a number, string, or boolean).
javascript

Copy code
import { ref } from 'vue'

const count = ref(0)
count.value++ // Accessing and modifying ref's value
  • reactive() is used to create a reactive object or array. It wraps a plain object and ensures its properties are reactive.
javascript

Copy code
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  name: 'Vue'
})

state.count++ // Accessing and modifying reactive state

3. Computed Properties

In Vue 3’s Composition API, computed properties are created using the computed() function. Computed properties are values that are derived from other reactive data.

javascript

Copy code
import { computed, ref } from 'vue'

const count = ref(0)

const doubleCount = computed(() => count.value * 2)

In the example above, doubleCount will automatically update when count changes. Computed properties are cached based on their dependencies, so they only recompute when necessary.

4. Watchers

In Vue 3, watch() is used to watch for changes in reactive data or computed properties. It's useful for performing side effects when specific data changes.

javascript

Copy code
import { watch, ref } from 'vue'

const count = ref(0)

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

Here, the watch() function observes count and executes the callback whenever count changes.

Using the Composition API in Practice

Let’s go through an example to see the Composition API in action. We will build a simple counter application with a button to increase the count, and display the count’s double using a computed property.

vue

Copy code
<template>
  <div>
    <h1>Count: {{ count }}</h1>
    <h2>Double Count: {{ doubleCount }}</h2>
    <button @click="increment">Increment</button>
  </div>
</template>

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

// Define reactive state using ref()
const count = ref(0)

// Define a method to update the state
function increment() {
  count.value++
}

// Define a computed property
const doubleCount = computed(() => count.value * 2)
</script>

In this example:

  • We declare a reactive count variable using ref().
  • We create a method increment() to modify the count.
  • We use computed() to create a derived doubleCount property that automatically updates when count changes.

This is a simple use case, but as your application grows, you’ll see how this approach scales better than using the Options API, especially when components become more complex.

Creating Reusable Logic with Composables

One of the biggest advantages of the Composition API is the ability to extract reusable logic into "composables." Composables are functions that encapsulate specific pieces of logic that can be shared across components.

For instance, let’s say we want to create a custom composable to handle a counter's logic:

javascript

Copy code
// useCounter.js
import { ref } from 'vue'

export function useCounter() {
  const count = ref(0)

  function increment() {
    count.value++
  }

  return {
    count,
    increment
  }
}

Now, in any component, you can import and use this logic:

vue

Copy code
<template>
  <div>
    <h1>Count: {{ count }}</h1>
    <button @click="increment">Increment</button>
  </div>
</template>

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

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

This approach makes it easy to share logic and maintain modular code. You can create multiple composables for different functionalities (e.g., form handling, authentication, data fetching) and use them in various components.

Advanced Features of the Composition API

1. Provide / Inject

Vue’s Composition API also introduces the provide() and inject() functions for dependency injection, which allow you to share data between components without passing it through props.

javascript

Copy code
// ParentComponent.vue
<script setup>
import { provide } from 'vue'

const theme = 'dark'
provide('theme', theme)
</script>
javascript

Copy code
// ChildComponent.vue
<script setup>
import { inject } from 'vue'

const theme = inject('theme')
console.log(theme) // 'dark'
</script>

This pattern is particularly useful for sharing global states (e.g., authentication status, user preferences) across deep component hierarchies.

2. Lifecycle Hooks in Composition API

With the Composition API, you can also use lifecycle hooks such as onMounted(), onBeforeUnmount(), onUpdated(), and others. These hooks replace the options like mounted, created, and destroyed from the Options API.

javascript

Copy code
import { onMounted } from 'vue'

onMounted(() => {
  console.log('Component has been mounted!')
})

This makes lifecycle hooks more predictable and reusable within composables.

Conclusion

The Composition API in Vue 3 represents a significant shift in how we write and organize our Vue components. It offers greater flexibility, scalability, and reusability of logic, making it easier to manage complex applications and codebases. By using ref(), reactive(), computed(), watch(), and custom composables, you can write more modular and maintainable code.

While the Options API still has its place for smaller applications or quick prototypes, the Composition API provides better tools for large, production-level Vue applications, especially as the complexity of the app increases.

The Composition API is a powerful addition to Vue.js that will enhance the way developers build and manage their applications. By learning and adopting it, you can future-proof your skills and take full advantage of Vue 3’s potential.

Tags

vue javascript frontend web-development composition-api
A

admin

Technical Writer & Developer

Author of 16 articles on Fusion_Code_Lab. Passionate about sharing knowledge and helping developers grow.

Discussion (0)

Join the discussion by logging in to your account

Log In to Comment

Related Articles

Unlocking the Power of Flask Blueprints

Unlocking the Power of Flask Blueprints

A Guide to Building Modular Applications

Read More →
Redis Caching Strategies for High-Performance Applications
Mastering The Flask Web Framework

Mastering The Flask Web Framework

A Deep Dive into Building Scalable Web Applications

Read More →