Until Vue 2, we only had one way of writing components in a Vue program. But, with improvements and up-gradation of Vue 2 to Vue 3, we can now write components differently using the Composition
The Composition API allows developers to write code with more flexibility, and it allows users to integrate TypeScript with their program.
This API modifies the previously used Options API in Vue 2 and includes a relatively more straightforward way of writing data
, computed
, method
, watches
, etc.
Note: Check out the official documentation of Composition API
. here https://vuejs.org/api/#composition-api
Composition API allows a user to write components and composition functions, such as
To install the Composition API in our Vue 2 or Vue 3 program, we execute the following command in our terminal.
npm install --save @vue/composition-api
If you don’t have
installed, then click npm
node package manager . here https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
Let’s write a code example to understand the working of Composition API in Vue.
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')
Note:
{{}}
: These are place-holders used for data.v-model
: This is used for two-way binding. It binds the value ofelements to application data. HTML HyperText Markup Language The main difference between the Options API in Vue 2 and Composition API in Vue 3 is the newly introduced
setup()
function insideexport default
. Thesetup()
function is the starting point of this API and is executed right before the component is created. This function allows the reusability of certain components.
Lines 1–5: We have the <template>
tag that includes a <div>
element. This div takes input from the user and passes whatever is written inside the textbox. We can see this in the output above when we press “Run”.
Line 8: In order to use the ref
, computed
, or other methods, we have to define them. The import
statement defines these methods so that we can use them in our code.
Line 11: Using the setup()
function, we can make reactive states and standalone primitive values (such as strings
, boolean
, etc.) using reactive
and ref
methods, respectively.
Line 12: We use the day
object, which passes the input value to ref
using placeholders or {{}}
.
Line 13: We use the computed()
method. The computed()
method is a new method introduced in Vue 3, which we can use to implement logic in our setup()
function. Notice that we use day.value
. This is because day
has a type of ref
, whereas in the <template>
tag, the internal value is directly accessible.
Free Resources