Vue Watch Computed Property

Posted on  by admin

Vue 3 is in beta and it’s subject to change. Vue 3 is the up and coming version of Vue front end framework. It builds on the popularity and ease of use of Vue 2. In this article, we’ll look at Vue computed properties and watchers.

We can add computed properties to derive some from an existing property. For instance, we can write:. We added the message property to the object we return in data .

Then we added the computed property to the object we passed into createApp . Methods are inside it getters, so we return things derived from other properties. The method must be synchronous.

Conclusion

Now when we type in something to the input, we’ll see the reversed version displayed below it. We can achieve the same result by running a method to reverse the string. But it wouldn’t be cached based on their dependency if we use a regular method to return derived data.

Computed properties are cached based on the original reactive dependencies. As long as this.message stays the same, reversedMessage won’t be run.

However, if we have dependencies that aren’t reactive in our computed property, then the method won’t run. In this case, we’ve to use methods to make them update.

Watchers

So something like:. We can have setters in our computed properties. For instance, we can write:. We have the firstName and lastName properties in the object we return with data . Then we can create the getter for the fullName property by returning the 2 properties combined into one string.

The setter would be the set method which takes the newValue and then split it back into its parts. We set the this.firstName and this.lastName based on the combined string we have returned from get .

Computed