vuejs
  1. vuejs-computed-properties

VueJs Computed Properties

Syntax

new Vue({
  computed: {
    propertyName: function() { /* computed function body */ }
  }   
})

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>

<div id="app">
  <input v-model="firstName">
  <input v-model="lastName">

  <h3>Full Name: {{ fullName }}</h3>
</div>

<script>
new Vue({
  el: "#app",
  data: {
    firstName: "",
    lastName: ""
  },
  computed: {
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
  },
});
</script>

</body>
</html>

Output

The above example will display two input fields for the user's first and last name. It will also display the user's full name as a computed property below the input fields.

Explanation

Computed properties in VueJs allow data that is derived from existing data to be automatically updated, based on changes to its dependencies without you having to manually write change watchers. A computed property is a function that returns a value based on other values in the Vue instance. A computed property's value is cached and only recalculated when its dependencies change.

Use

Computed properties in VueJs are used to retrieve, manipulate, and return data based on other data in a Vue instance. They are particularly useful for performing calculations or manipulating the display of data based on the state of an application. Computed properties can improve the performance of your Vue application by caching the results of the computation until one of its dependencies changes.

Important Points

  • Computed properties are cached based on their dependencies and are only recomputed if their dependencies change.
  • Computed properties can be used to perform calculations or manipulate data without writing a lot of logic in the template.
  • Always use computed properties for properties that depend on other properties and only use methods when you need to perform an action, such as making an API call.
  • Avoid using computed properties that have side effects, such as modifying data in your component or making asynchronous API calls.

Summary

Computed properties in VueJs are a powerful tool for manipulating and displaying data based on other data in a Vue instance. By caching the results of computations and updating them only when their dependencies change, they help improve the performance of your Vue application. Understanding how to use computed properties effectively, by avoiding side effects and using them for data manipulation will help you write more efficient and maintainable code.

Published on: