Top 10 Vue Composition API Tips for Better Development
Looking for a Postman alternative?
Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!
Top 10 Vue Composition API Tips for Better Development
Introduction to the Composition API in Vue 3
The Composition API is a set of APIs in Vue 3 that allows developers to author Vue components using imported functions instead of declaring options. It offers clean and efficient logic reuse with composable functions, solving the drawbacks of mixins in the Option API. The Composition API provides a more flexible and organized way to manage complex component logic. In this article, we will explore the benefits of migrating to the Composition API and provide a step-by-step guide for migrating components.
Benefits of migrating to the Composition API
Migrating to the Composition API offers several advantages for Vue developers. One of the key benefits is improved code organization and reusability. With the Composition API, you can create reusable composable functions that encapsulate specific logic and can be easily used in multiple components. This promotes code reusability and makes it easier to maintain and update the codebase.
The Composition API also makes it easier to manage complex component logic. With the Option API, it can sometimes be challenging to understand and manage the flow of data and logic in a component. The Composition API allows you to break down complex logic into smaller composable functions, making it easier to reason about and maintain.
Another benefit of the Composition API is the increased flexibility and simplicity in defining props, event emitters, data, methods, computed properties, watchers, and lifecycle hooks. The Composition API provides dedicated functions for each of these features, making it easier to understand and work with these concepts.
Step-by-step guide for migrating components
Migrating components to the Composition API involves several steps. In the following sections, we will go through each step in detail.
3.1 Components
In the Composition API, you don’t need to explicitly declare the components you want to use. Simply import the components and they will be available in your template. This eliminates the need for the components
property in the Option API.
<template>
<ChildComponent />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
};
</script>
With the Composition API:
<template>
<ChildComponent />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
</script>
3.2 Props
To define props in the Composition API, you can use the defineProps
method inside the script setup
tag. This method allows you to specify the type and required properties for each prop.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true,
},
},
};
</script>
With the Composition API:
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
message: {
type: String,
required: true,
},
});
</script>
3.3 Event emitters
In the Composition API, you can use the defineEmits
method to define event emitters. This method takes an array of event names.
<template>
<button @click="handleButtonClick">Click me</button>
</template>
<script>
export default {
methods: {
handleButtonClick() {
this.$emit('button-clicked');
},
},
};
</script>
With the Composition API:
<template>
<button @click="handleButtonClick">Click me</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const handleButtonClick = () => {
emit('button-clicked');
};
const emits = defineEmits(['button-clicked']);
</script>
3.4 Data
In the Composition API, you can import the ref
function from Vue to define reactive data. Use the ref
function to create a reactive reference to the initial value of a variable.
<template>
<div>{{ count }}</div>
<button @click="increment">Increment</button>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
increment() {
this.count++;
},
},
};
</script>
With the Composition API:
<template>
<div>{{ count.value }}</div>
<button @click="increment">Increment</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => {
count.value++;
};
</script>
3.5 Methods
In the Composition API, methods are now simple JavaScript functions. You can define them as regular functions and use them in your component.
<template>
<div>{{ message }}</div>
<button @click="uppercaseMessage">Uppercase</button>
</template>
<script>
export default {
data() {
return {
message: 'Hello',
};
},
methods: {
uppercaseMessage() {
this.message = this.message.toUpperCase();
},
},
};
</script>
With the Composition API:
<template>
<div>{{ message }}</div>
<button @click="uppercaseMessage">Uppercase</button>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello');
const uppercaseMessage = () => {
message.value = message.value.toUpperCase();
};
</script>
3.6 Computed properties
In the Composition API, you can import the computed
method from Vue to define computed properties. The computed
method takes a callback function that returns the value of the property.
<template>
<div>{{ fullName }}</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe',
};
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
},
},
};
</script>
With the Composition API:
<template>
<div>{{ fullName }}</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`;
});
</script>
3.7 Watchers
In the Composition API, you can import the watch
method from Vue to watch for changes in reactive data. The watch
method takes the data to watch and a callback function to execute when the data changes.
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
watch: {
count(newValue, oldValue) {
console.log(`Count changed from ${oldValue} to ${newValue}`);
},
},
};
</script>
With the Composition API:
<template>
<div>{{ count }}</div>
</template>
<script setup>
import { ref, watch } from 'vue';
const count = ref(0);
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
</script>
3.8 Created
Inside the script setup
, you can add a console.log
statement to be executed when the component is created.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
created() {
console.log('Component created');
},
data() {
return {
message: 'Hello',
};
},
};
</script>
With the Composition API:
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const message = ref('Hello');
onMounted(() => {
console.log('Component created');
});
</script>
3.9 On Mount
In the Composition API, you can use the onMounted
method to run code after the component is mounted. Inside the callback function, you can perform any necessary operations, such as fetching data from an API.
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
// Fetch data from API
},
},
};
</script>
With the Composition API:
<template>
<div>{{ count }}</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const count = ref(0);
const fetchData = () => {
// Fetch data from API
};
onMounted(() => {
fetchData();
});
</script>
3.10 Lifecycle hooks
In the Composition API, you can use lifecycle hooks like onBeforeUpdate
, onUpdated
, onBeforeUnmount
, and onUnmounted
to perform actions at specific stages of a component's lifecycle.
<template>
<div>{{ count }}</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
beforeUpdate() {
console.log('Component is about to update');
},
updated() {
console.log('Component has updated');
},
beforeUnmount() {
console.log('Component is about to unmount');
},
unmounted() {
console.log('Component has unmounted');
},
};
</script>
With the Composition API:
<template>
<div>{{ count }}</div>
</template>
<script setup>
import { ref, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
const count = ref(0);
onBeforeUpdate(() => {
console.log('Component is about to update');
});
onUpdated(() => {
console.log('Component has updated');
});
onBeforeUnmount(() => {
console.log('Component is about to unmount');
});
onUnmounted(() => {
console.log('Component has unmounted');
});
</script>
Conclusion
Migrating from the Option API to the Composition API in Vue 3 provides numerous benefits, such as improved code organization, reusability, and simpler logic management. In this article, we have provided a step-by-step guide for migrating components using the Composition API. By following these steps, you can leverage the power and flexibility of the Composition API in your Vue projects. Experiment with these concepts and explore the possibilities that the Composition API offers. Happy coding!
Looking for a Postman alternative?
Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!