tezvyn:

Vue Computed Properties: Derived Values for Cleaner Templates

AI-drafted, machine-checkedSource: vuejs.orgintermediate

A Vue computed property is a reactive 'formula' that derives its value from other data. Use it to move complex logic out of your templates, keeping them clean and readable.

WHY IT EXISTS: In-template expressions are convenient for simple operations. However, putting too much logic into your templates makes them bloated, hard to read, and difficult to maintain. Computed properties were created to move this complex, reactive logic out of the template and into the component's script, separating calculation from presentation.

THE MENTAL MODEL: Think of a computed property as a reactive 'formula' that derives its value from other data properties. It's not a piece of data you set yourself, but rather a value that is calculated based on other reactive state. When the underlying state changes, the computed property automatically updates to reflect the new result.

HOW IT WORKS: You declare a computed property by providing a getter function. For example, in the Options API, you add it to the computed object; in the Composition API, you use the computed() function. Vue inspects this function to see which reactive properties it depends on. It then caches the result. The getter function will only re-run, and the value will only be re-calculated, when one of its tracked dependencies changes.

WHEN TO USE IT: Use a computed property for any complex logic that involves reactive data. It is the recommended approach when a calculation is needed to derive a value for display. This keeps your templates clean and declarative. For example, instead of a complex ternary operator in the template, you can reference a computed property by name, making the template's intent much clearer. It's also ideal if you need to use the same calculated value in multiple places.

WHEN NOT TO USE IT: For extremely simple, one-off operations, an in-template expression can be acceptable and more direct. The primary purpose of a computed property is to handle 'complex logic'. If the logic is not complex (e.g., count + 1) and isn't repeated throughout the template, a computed property might be overkill.

ONE CANONICAL EXAMPLE: Imagine a component has reactive data for an author with a list of books: author: { books: ['Book 1', 'Book 2'] }. Instead of putting {{ author.books.length > 0 ? 'Yes' : 'No' }} in your template, you create a computed property. In your script, you define publishedBooksMessage() which returns 'Yes' or 'No' based on the array's length. Your template then becomes a much cleaner {{ publishedBooksMessage }}. If the books array is emptied, the message automatically updates to 'No'.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.