Vue.js Computed Properties
Computed Properties Keyword:computed。
Computed properties are very useful when dealing with some complex logic.
You can look at the following example of reversing a string:
In Example 1, the template becomes very complex and is not easy to read and understand.
Next, let's look at an example that uses computed properties:
Example 2
Try it Yourself »
In Example 2, a computed property named reversedMessage is declared.
The provided function will be used as the getter for the property vm.reversedMessage.
vm.reversedMessage depends on vm.message. When vm.message changes, vm.reversedMessage will also update.
computed vs methods
We can use methods instead of computed. The effect of the two is the same, but computed is cached based on its dependencies, and only re-evaluates when the related dependencies change. When using methods, the function will always be called and executed again on re-rendering.
Example 3
Try it Yourself »
It can be said that using computed gives better performance, but if you don't want caching, you can use the methods property.
computed setter
A computed property only has a getter by default, but you can also provide a setter when needed:
Example 4
Try it Yourself »
From the example's running result, when vm.site = 'Example http://www.example.com'; is executed, the setter will be called, and vm.name and vm.url will also be updated accordingly.
