When using composition API, we declare functions inside the setup()
function instead of methods. The function is then returned by the setup() function to be used in the template of the component.
In this article, we will look at how to declare and use these functions instead of methods.
We will begin by creating a new application using Vue CLI.
❯ vue create composition-function-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd composition-function-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
We first look at how to declare a method using the options API and later convert it to function using the composition API.
Declaring methods using option API
Let’s open up the App.vue
file and add a method to it.
<!-- App.vue -->
<template>
<h1>Clicked {{ count }} times</h1>
<button @click="increment">Increment</button>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
increment() {
this.count++;
},
},
};
</script>
In this example, we have a method increment()
that increments the count
property every time the button is clicked.
Let’s look at how to convert this method to a function using the composition API.
Declaring functions using composition API
The first thing we need to do when using composition API is to create a setup()
function that will hold the properties and functions within it.
In our example, we will use the ref
function to declare the reactive object.
import { ref } from "vue";
export default {
setup() {
const count = ref(0);
return {
count,
};
},
};
Next, we will declare a function increment
inside the setup()
function that will increase the count every time the user clicks the button.
function increment() {
count.value++;
}
Notice, we are using count.value
instead of count
. This is because ref
returns an object with a property value
that holds the actual value assigned to count. This is, however, not required when using count
in the template since Vue unwraps the object automatically for us.
With these changes, our App.vue
will now look something like this.
<!-- App.vue -->
<template>
<h1>Clicked {{ count }} times</h1>
<button @click="increment">Increment</button>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment,
};
},
};
</script>
It is important to note that setup()
needs to return any function that we declare in order for them to be accessible in the component’s template.
return {
count,
increment,
}
This was a simple example to show you how we can declare and use functions in Vue.js when using composition API.