Reader small image

You're reading from  Frontend Development Projects with Vue.js 3 - Second Edition

Product typeBook
Published inMar 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803234991
Edition2nd Edition
Languages
Tools
Right arrow
Authors (4):
Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

View More author details
Right arrow

The Composition API

In the previous chapter, we learned how to establish data communication between nesting components using props, refs, and slots.

This chapter will introduce us to a new and scalable approach to writing components with the setup() lifecycle hook – the Composition API. By the end of the chapter, you will be able to write isolated composables (or custom hooks) to reuse in multiple components by using the Composition API with the setup() method, and build a scalable component system for your Vue project beyond the classic Options API.

This chapter covers the following topics:

  • Creating components with the setup() lifecycle method
  • Working with data
  • Understanding composable lifecycle functions
  • Creating your composable (custom hook)

Technical requirements

In this chapter, you need to set up a basic Vue project following the instructions in Chapter 1, Starting Your First Vue Project. Creating a single file Vue component is recommended to practice the examples and concepts mentioned easily.

You can find this chapter’s source code here: https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter05.

Creating components with the setup() lifecycle method

Starting from Vue 3.x, the Vue team has introduced the Composition API as a new way to compose Vue components within the setup() lifecycle method. As mentioned in Chapter 1, Starting Your First Vue Project, setup() is the first hook the Vue engine will run in a component’s lifecycle before the beforeCreate() hook. At this point, Vue hasn’t defined a component instance or any component data.

This lifecycle method runs once before the initialization and creation of a component and is part of the Options API. The Vue team has dedicated setup() to working with Composition API and any custom hooks (composables) written with the Composition API as an alternative approach to creating reactive components besides the Options API.

You can start using the setup() method with the following syntax:

setup(props, context) {
  // ...
  return {
  //...
  }
}

Setup() accepts two arguments...

Working with data

In the Options API, we use the data() method to initialize a component’s local state. By default, all the data properties received from data() are reactive, which can be overkill in many scenarios. Vue has introduced the ref() and reactive() functions, which allow us to decide which local states should be reactive and which shouldn’t be.

Setting a reactive local state with ref()

ref() is a function that accepts a single input parameter as the reactive data’s initial value and returns a reference object for the created reactive data state. We call this reference object a ref object. To start using ref(), you first need to import it from the vue package.

For example, we can create a reactive data called isLightOn, which accepts false as its initial value as follows:

import { ref } from 'vue';
const isLightOn = ref(false);

In the template section, you can access the value of isLightOn in the same way as before, as shown in...

Understanding composable lifecycle functions

In Chapter 1, Starting Your First Vue Project, we learned about the component’s lifecycle and its available hooks in Vue’s Options API. In the Composition API, these lifecycle hooks are now available as standalone functions and need to be imported from the vue package before use.

Generally, the lifecycle functions in the Composition API are similar to the ones from the Options API, with a prefix of on. For example, beforeMount() in the Options API is onBeforeMount() in the Composition API, and so on.

The following is the list of available lifecycle functions from the Composition API, ready to use within the setup() method or <script setup>:

  • onBeforeMount(): Before the first render of the component
  • onMounted(): After rendering and mounting the component to the DOM
  • onBeforeUpdate(): After starting the component’s update process, but before the actual rendering of the updated component
  • onUpdated...

Creating your composable (custom hook)

In many scenarios, we want to group some components’ logic into reusable code blocks for other components that share similar functionalities. In Vue 2.x, we use mixins to achieve this goal. However, mixins are not the best practical solution, and they can create code complexity due to the order of merging and invoking overlapping data and lifecycle hooks.

Starting from Vue 3.0, you can use the Composition API to divide the common data logic into small and isolated composables, using them to create a scoped data control in different components and return the created data if there is any. A composable is a regular JavaScript function that uses Composition API methods and performs data state management internally.

To get started, we create a new JavaScript (.js) file, which exports a function acting as the composable. In the following example, we create a useMessages composable, which returns a list of messages and some methods to modify...

Summary

Throughout this chapter, we learned about composing components using the Composition API and the setup() lifecycle hooks (or <script setup>) as an alternative to the Options API. We also learned how to use different Composition functions to create watchers and lifecycle callbacks to control our components’ local states.

Finally, we learned how to create our custom composable function based on the Composition API and other composables, making our components more organized and readable in groups of similar logic.

In the next chapter, we will explore how we can create global components using plugins and mixins and compose dynamic components.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781803234991
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (4)

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco