In Vue, computed properties are special properties that are derived from the Vue instance's data and are reactive, meaning they will automatically update when their dependencies change.
Computed properties are useful for performing data manipulation, calculations, and filtering in a Vue component, without directly modifying the component's data.
Reactivity: It automatically re-evaluates when its dependencies change, making them reactive.
Getter-Only: Computed properties should be defined as functions without setter functions. They are read-only by nature.
Caching: Computed properties are cached based on their dependencies. If the dependencies haven't changed, Vue.js will return the cached result instead of recalculating the property.
Conditional Logic: Compute boolean values or other derived values based on conditions.
Complex Calculations: Perform complex calculations based on various data properties.
Formatting: Format data for display, such as currency formatting, date formatting, etc.
Data Aggregation: Compute aggregated data from multiple data sources.
Filtering and Sorting: Compute filtered or sorted versions of lists based on user input or other criteria.
Computed properties are defined as functions in the "computed" property of a Vue component.
They return the result of some computation based on the component's data properties.
<template> <div> <h1> {{ fullName }} </h1> <p> {{ greetingMessage }} </p> </div> </template> <script> export default { name: "App", data() { return { firstName: 'Alice', lastName: 'Collin' }; }, computed: { fullName() { return this.firstName + ' ' + this.lastName; }, greetingMessage() { return "Welcome, " + this.fullName } } } </script>
<h1> {{fullName}} </h1>
Computed properties can be accessed in the template just like regular data properties.
Note: the "fullName" computed property is accessed within the template to display the full name.
Vue caches computed properties based on their dependencies.
This means that if the dependencies have not changed since the last evaluation, Vue will return the cached result instead of re-evaluating the computed property function.
computed: { fullName: { get() { return this.firstName + ' ' + this.lastName; }, set(value) { const names = value.split(' '); this.firstName = names[0]; this.lastName = names[names.length - 1]; } } }
Computed properties can also have a getter and setter, allowing us to define custom behaviour when reading and writing to the property.
Note: the "fullName" computed property has a custom "getter" and "setter" to handle reading and writing to the full name.