Calculate attribute
Expressions in templates are very convenient, but they are designed for simple calculations. Putting too much logic into a template can make it too heavy and difficult to maintain. Such as:
Here, templates are no longer simple declarative logic. You have to look at it for a while to realize that this is a flipped string that wants to display the variable message. This becomes even more difficult when you want to include the rollover string in multiple places in the template.
So, for any complex logic, you should use computed properties.
In-project examples
Most of the pages in the asset Workbench use these two buttons, so they encapsulate the components
Computed attributes are used in the component to control the width and alignment of the query buttons
Calculate the property cache vs method
We can achieve the same effect by calling methods in expressions, for example:
We can define the same function as a method rather than a calculated property. The end result is exactly the same. The difference, however, is that computed attributes are cached based on their reactive dependencies. They are reevaluated only when the associated reactive dependencies change. This means that as long as the Message has not changed, multiple visits to the reversedMessage computed property will immediately return the previous computed result without having to execute the function again.
This also means that the following computed attributes will not be updated because date.now () is not a reactive dependency:
Compute properties vs listen properties
Vue provides a more general way to observe and respond to changes in data on Vue instances: listening properties. It’s easy to abuse Watch when you have some data that needs to change with other data — especially if you’ve used AngularJS before. However, it is often better to use computed properties rather than imperative Watch callbacks. Consider this example:
The code above is imperative and repetitive. Compare this to the version of the calculated property:
The listener
While computing properties is more appropriate in most cases, sometimes a custom listener is required. That’s why Vue provides a more generic way to respond to changes in data with the Watch option. This approach is most useful when asynchronous or expensive operations need to be performed when data changes.
In-project examples
💠— — — — — — — — — — — — — — — — — — — — ðŸ’
The official, for example,
In this example, using the Watch option allows us to perform an asynchronous operation (accessing an API), limit how often we perform that operation, and set the intermediate state until we get the final result. These are all things you can’t do with computed properties.
In addition to the Watch option, you can also use the imperative VM.$watch API.