Vue 3 Composition API: Basics and Patterns
Upgrade your Vue.js skills with our comprehensive guide to the Composition API in Vue 3. Discover powerful techniques to build better web applications.
This blog is a part of our “Engineering at Arcana” series, and is written by our Frontend Developer Shrinath Prabhu.
Vue 3 introduced Composition API which allows developers to write components in a better way. Using this API, developers can group the logical pieces of code together, which in turn helps write readable code.
Composition API is a built in feature in Vue 3 and is also available in Vue 2 via @vue/composition-api plugin.
Before Composition API was introduced, Vue 2 was using Options API. While developers can still use Options API in Vue 3, the problem with it is that one single topic would be fragmented across different options such as data() or props, certain methods, some lifecycle hooks (mounted(), created(), and more), and watchers (watch).
With Composition API, you can organise code into smaller logical pieces, group them together, and even reuse them when required.
Let’s see a basic example to understand the difference of coding structure between Options API and Composition API.
This is how our highly logical code looks like in the Options API:
Now the same code can have separation of logic in the Composition API and it’ll look something like this:
Clearly the Composition API code looks a lot cleaner since it can have separation of logic.
The above code can be even more simplified by using the