Vue.js / Vue Composition API

Working with Computed Properties

In this tutorial, you'll learn how to work with computed properties in Vue 3. Computed properties are a powerful feature that allows you to create reactive data that depends on ot…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores Vue 3's Composition API for structuring applications.

Introduction

In this tutorial, we will explore how to work with computed properties in Vue 3. Computed properties are a feature that enables you to create reactive data that depends on other data. This means that when the dependent data changes, the computed property automatically updates to reflect these changes.

By the end of this tutorial, you will:

  • Understand what computed properties are.
  • Know how to create and use computed properties in a Vue 3 application.
  • Learn best practices when working with computed properties.

Prerequisites:

  • Basic knowledge of JavaScript.
  • Familiarity with Vue.js.

Step-by-Step Guide

Understanding Computed Properties

Computed properties are functions you define in the Vue instance's computed property. They are used to compute derived data based on your instance's data. Computed properties are lazy-loaded, meaning they only re-evaluate when their reactive dependencies change.

Creating a Computed Property

To create a computed property, you add a function to the computed property in your Vue instance. The function should return the computed value.

const app = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
    }
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`
    }
  }
})

In this example, fullName is a computed property that depends on firstName and lastName. Whenever firstName or lastName changes, fullName will be updated.

Code Examples

Example 1: Basic Computed Property

const app = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
    }
  },
  computed: {
    // fullName is a computed property that returns the full name
    fullName() {
      return `${this.firstName} ${this.lastName}`
    }
  }
})

// Mount the app
app.mount('#app')

// In your template, you can use the computed property as follows:
// <p>{{ fullName }}</p>
// This will output: "John Doe"

In this example, fullName is a computed property that concatenates firstName and lastName.

Example 2: Computed Property with a Setter

Computed properties can also have a setter, which is used when you want to change the computed property's value.

const app = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
    }
  },
  computed: {
    fullName: {
      get() { // getter
        return `${this.firstName} ${this.lastName}`
      },
      set(value) { // setter
        const parts = value.split(' ')
        this.firstName = parts[0]
        this.lastName = parts[1]
      }
    }
  }
})

// Mount the app
app.mount('#app')

// You can now set fullName like this:
// app.fullName = 'Jane Doe'
// This will update firstName and lastName accordingly

In this second example, we've added a setter to the fullName computed property. Now when you set fullName, it updates firstName and lastName.

Summary

In this tutorial, we've learned about computed properties in Vue 3. We've seen how they allow you to create reactive data that automatically updates when its dependencies change. We've also learned how to create computed properties with both getters and setters.

Next, you could explore Vue's other reactive features, such as watchers and methods.

Additional resources:

Practice Exercises

  1. Create a Vue app with a data property count and a computed property isEven that returns whether count is an even number.

  2. Extend the previous exercise by adding a button that increases count and displays a message using isEven.

  3. Create a Vue app with data properties firstName and lastName, and computed properties fullName and initials. fullName should be a getter and setter, and initials should return the first letters of firstName and lastName.

Solutions and explanations to these exercises will be provided, but try to solve them on your own first to get the most out of this tutorial.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help