Vue Composition API
An alternative to using the Options API, which is used throughout this article, for creating Vue apps is to use the Composition API.
We have greater freedom to build code with Composition API, but it is seen to be less user-friendly and requires a deeper understanding.
The Composition API
Rather than writing logic using the Vue instance structure we are accustomed to using Options API, Composition API allows us to write logic using imported Vue functions.
Using the Composition API, one could create a Vue application that, at the touch of a button, reduces the quantity of typewriters kept in storage:
Example
App.vue:
Example
Typewriters left in storage: {{ typeWriters }}
"{{ storageComment }}"
The setup attribute in the example above, on line 9, facilitates the use of the Composition API. Variables and functions, for instance, can be used right inside the <template> by utilizing the setup element.
Before being utilized, ref and calculated on line 10 need to be imported. To use computed properties or declare reactive variables in Options API, no imports are required.
The ‘typewriters’ property is declared as reactive on line 12 with ’10’ as the initial value using ref.
Declaring the ‘typewriters’ property as reactive entails that whenever the value of the ‘typewriters’ property is modified, the line {{ typewriters }} in the <template> will be automatically re-rendered to reflect the revised value. Option API eliminates the requirement for data properties to be specifically specified as reactive; instead, it allows them to become reactive when the application is constructed.
If the above was written in Options API, the’remove()’ function declared on line 14 would be declared under the Vue property’methods’.
If the example was written in the Options API, the calculated property’storageComment’ on line 20 would be declared under the Vue property ‘computed’.
The Options API
The remainder of this lesson makes use of the Options API.
Because of its recognized form and ease of use for beginners, the Options API was selected for this course.
The structure of the Options API, for instance, clearly divides the computed properties, methods, and data properties into distinct areas of the Vue instance.
This is the Options API-written example mentioned above:
Example
App.vue:
Example
Typewriters left in storage: {{ typeWriters }}
"{{ storageComment }}"