diff --git a/src/guide/computed.md b/src/guide/computed.md index 79dc8bd76c..ce4754485b 100644 --- a/src/guide/computed.md +++ b/src/guide/computed.md @@ -2,45 +2,69 @@ ## Computed Properties -In-template expressions are very convenient, but they are meant for simple operations. Putting too much logic in your templates can make them bloated and hard to maintain. For example: +In-template expressions are very convenient, but they are meant for simple operations. Putting too much logic in your templates can make them bloated and hard to maintain. For example, if we have an object with a nested array: + +```js +Vue.createApp({ + data() { + return { + author: { + name: 'John Doe', + books: [ + 'Vue 2 - Advanced Guide', + 'Vue 3 - Basic Guide', + 'Vue 4 - The Mystery' + ] + } + } + } +}) +``` + +And we want to display different messages depending on if `author` already has some books or not ```html -
Has published books:
+ {{ author.books.length > 0 ? 'Yes' : 'No' }}Original message: "{{ message }}"
-Computed reversed message: "{{ reversedMessage }}"
+Has published books:
+ {{ publishedBooksMessage }}Reversed message: "{{ reverseMessage() }}"
+{{ calculateBooksMessage() }}
``` ```js // in component methods: { - reverseMessage() { - return this.message.split('').reverse().join('') + calculateBooksMessage()() { + return this.author.books.length > 0 ? 'Yes' : 'No' } } ``` -Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that **computed properties are cached based on their reactive dependencies.** A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as `message` has not changed, multiple access to the `reversedMessage` computed property will immediately return the previously computed result without having to run the function again. +Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that **computed properties are cached based on their reactive dependencies.** A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as `author.books` has not changed, multiple access to the `publishedBooksMessage` computed property will immediately return the previously computed result without having to run the function again. This also means the following computed property will never update, because `Date.now()` is not a reactive dependency: