Vue 3 composition API with Typescript class components

take it_
2 min readOct 23, 2020

This post explains how to add the composition API to Vue 3 + Typescript class components.

Vue 3 is great, specially the composition API is an awesome new feature. Migrating Vue 2 class based components to Vue 3 is not difficult, except for some small changes like changing @Component to @Options everything is staying the same.

After migrations of Vue 3 with class components, we were ready to add the composition API. This was harder than we expected because official docs don’t provide example for this specific setup https://composition-api.vuejs.org/.

Earlier designs of Vue 3 had the class API included however this has been cancelled: https://github.com/vuejs/rfcs/pull/17#issuecomment-494242121

The reasons why not to use the class components with Vue 3 are understandable (see link above) but most Vue 2 + Typescript projects are using the class based components. For easier migration, it would be easier to keep the class components.

This is an example with a small module using the composition API.

A standard module with a function fetching data

Calling the “get” function in the Vue component can be done like this:

the ‘setup’ function returns the module and sets data ‘artists’

Now the ‘artists’ module can be rendered in the template.

All the logic for ‘artists’ is located in ‘user-artists.ts’ and easy accessible in the component template.

In the below Github repository you can find a full example, using two modules:

We hope this post helps you to understand how to use the composition API with Typescript class components in Vue 3.

--

--

take it_

As a design and development agency from Berlin, we help fast-growing companies with scalable Storyblok websites. https://www.takeit.agency