Skip to main content

Vue.js Composition API

Introduction to Vue.js Composition API

In this tutorial, we will delve into the Vue.js Composition API - a new feature introduced in Vue 3. The Composition API is an advanced feature that provides a set of additive, function-based APIs that allow flexible composition of component logic.

The Composition API is not a replacement for Vue's current Options API but is an additional feature that can be used alongside the Options API.

Why Use the Vue.js Composition API?

When working with larger and more complex components, the Options API can become difficult to manage. The Composition API provides a way to encapsulate and reuse functionalities across different components, making your code more readable and maintainable.

Setting Up

Before we dive in, ensure you have Vue 3 installed in your project. If you are using Vue 2, you can add the Composition API as a plugin.

Using the Composition API

In Vue 3, a new component option setup is available. The setup function is the entry point for using the Composition API within a component. It runs before the component is created, right after props are resolved.

Here's the basic syntax of the setup function:

export default {
props: {
msg: String,
},
setup(props) {
// composition functions go here
},
}

Reactive State with ref and reactive

To create a reactive state within the setup function, you can use ref and reactive.

ref

A ref creates a reactive reference to a value.

import { ref } from 'vue'

export default {
setup() {
const count = ref(0)

function increment() {
count.value++
}

return {
count,
increment,
}
},
}

reactive

reactive creates a reactive object.

import { reactive } from 'vue'

export default {
setup() {
const state = reactive({
count: 0,
increment() {
state.count++
},
})

return state
},
}

Watchers

You can use the watch function to respond to changes on a reactive property.

import { ref, watch } from 'vue'

export default {
setup() {
const count = ref(0)

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

return {
count,
}
},
}

Computed Properties

The computed function is used to create computed properties.

import { ref, computed } from 'vue'

export default {
setup() {
const count = ref(0)
const doubled = computed(() => count.value * 2)

return {
count,
doubled,
}
},
}

Conclusion

The Vue.js Composition API is a powerful tool for organizing and reusing code. By encapsulating logic into composable functions, your code can become more maintainable and easier to test. While it may seem complex at first, with practice, you'll find the Composition API to be a great addition to your Vue.js toolkit. Happy coding!