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

Working with Data

In the previous chapter, you learned about the essentials of the Vue API and how to work with single-file Vue components. Building on these foundations, this chapter further explores different approaches to controlling data within a Vue component.

You will learn how to utilize Vue’s powerful data reactivity and cache system through computed properties and how to set up advanced watchers to observe the component’s data changes. You will also learn how to utilize asynchronous methods to fetch and handle data for your Vue components. By the end of this chapter, you will be able to watch, manage, and manipulate data from various sources in your Vue.js components.

So, in this chapter, we will cover the following topics:

  • Understanding computed properties
  • Understanding computed setters
  • Exploring watchers
  • Watching nested properties
  • Exploring async methods and data fetching
  • Comparing methods, watchers, and computed props
...

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. You can create a single file Vue component to easily practice the examples and concepts mentioned.

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

Understanding computed properties

Computed properties are unique data types that will reactively update only when the source data used within the property is updated. By defining a data property as a computed property, we can perform the following activities:

  • Apply custom logic on the original data property to calculate the computed property’s value
  • Track the changes of the original data property to calculate the updated value of the computed property
  • Reuse the computed property as local data anywhere within the Vue component

By default, the Vue engine automatically caches the computed properties, making them more performant at updating the UI than using the property of the returned value of data, or using a Vue component’s method.

The syntax of a computed property is like writing a component method with a return value, nested under the computed property of the Vue component:

export default {
  computed: {
    ...

Understanding computed setters

By default, computed data is a getter only, which means it will only output the outcome of your expression. In some practical scenarios, when a computed property is mutated, you may need to trigger an external API or mutate the original data elsewhere in the project. The function performing this feature is called a setter.

Using a setter in a computed property allows you to reactively listen to data and trigger a callback (setter) that contains the returned value from the getter, which can optionally be used in the setter.

But first, let’s look at JavaScript ES5’s getter and setter. Starting from ES5, you can use the built-in getter and setter to define Object accessors, such as the following:

  • get to bind the Object property to a function that returns a value for that property whenever it is looked up, as shown here:
    const obj  = {
      get example() {
        return 'Getter'
     ...

Exploring watchers

Vue watchers programmatically observe component data and run whenever a particular property changes. Watched data can contain two arguments: oldVal and newVal. This can help you when writing expressions to compare data before writing or binding new values. Watchers can observe objects as well as other types, such as string, number, and array types.

In Chapter 1, Starting Your First Vue Project, we introduced life cycle hooks that run at specific times during a component’s lifespan. If the immediate key is set to true on a watcher, then when this component initializes, it will run this watcher on creation. You can watch all keys inside any given object by including the key and value deep: true (the default is false).

To clean up your watcher code, you can assign a handler argument to a defined component’s method, which is considered best practice for large projects.

Watchers complement the usage of computed data since they passively observe...

Watching nested properties

When using Vue.js to watch a data property, you can observe changes belonging to nested keys of an object, rather than observing the changes to the object itself.

This is done by setting the optional deep property to true:

data() {
  return {
      organization: {
        name: 'ABC',
        employees: [
            'Jack', 'Jill'
        ]
      }
  }
},
watch: {
    organization: {
      handler(v) {
        this.sendIntercomData()
      },
      deep: true,
      immediate: true,
 ...

Exploring async methods and data fetching

Asynchronous functions in JavaScript are defined by the async syntax and return a Promise. These functions operate asynchronously via the Event loop, using an implicit promise, which is an object that may return a result in the future.

As part of the JavaScript language, you can declare asynchronous blocks of code inside a Vue component’s method by including the async keyword in front of a method.

You can use Promise chaining methods, such as the then() and catch() functions or try the await syntax of ES6 inside these Vue methods and return the results accordingly.

Here is an example using the built-in fetch API to fetch data inside a component method as an asynchronous function with async/await keywords:

export default {
  methods: {
    async getAdvice() {
      const response =
        await fetch('https://api.adviceslip...

Comparing methods, watchers, and computed properties

Methods are best used as a handler to an event occurring in the DOM, and in situations where you need to call a function or perform an API call, for example, Date.now(). All values returned by methods are not cached.

For example, you can compose an action denoted by @click, and reference a method:

<template>
    <button @click="getDate">Click me</button>
</template>
<script>
export default {
    methods: {
        getDate() {
            alert(Date.now())
        }
    }
}
</script>

This code block will display an alert bar with the current Unix epoch time whenever a user clicks on the Click me button. Methods should not be used to display computed data, since the return value of...

Summary

In this chapter, you were introduced to Vue.js computed and watch properties, which allow you to observe and control reactive data. You also explored how to use methods to asynchronously fetch data from an API using the axios library. Then, you learned how to dynamically compose the received data into different outputs within the Vue template using computed props. The differences between using methods and computed and watch properties were demonstrated by building search functionality using each method.

The next chapter will cover Vite and show you how to use Vue DevTools to manage and debug your Vue.js applications that use these computed properties and events.

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