Computed Properties and Watchers

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:

  1. <div id="example">
  2. {{ message.split('').reverse().join('') }}
  3. </div>

At this point, the template is no longer simple and declarative. You have to look at it for a second before realizing that it displays message in reverse. The problem is made worse when you want to include the reversed message in your template more than once.

That’s why for complex logic that includes reactive data, you should use a computed property.

Basic Example

  1. <div id="computed-basic">
  2. <p>Original message: "{{ message }}"</p>
  3. <p>Computed reversed message: "{{ reversedMessage }}"</p>
  4. </div>
  1. const vm = Vue.createApp({
  2. data() {
  3. return {
  4. message: 'Hello'
  5. }
  6. },
  7. computed: {
  8. // a computed getter
  9. reversedMessage() {
  10. // `this` points to the vm instance
  11. return this.message
  12. .split('')
  13. .reverse()
  14. .join('')
  15. }
  16. }
  17. }).mount('#computed-basic')

Result:

See the Pen Computed basic example by Vue (@Vue) on CodePen.

Here we have declared a computed property reversedMessage. The function we provided will be used as the getter function for the property vm.reversedMessage:

  1. console.log(vm.reversedMessage) // => 'olleH'
  2. vm.message = 'Goodbye'
  3. console.log(vm.reversedMessage) // => 'eybdooG'

Try to change the value of message in the application data and you will see how reversedMessage is changing accordingly.

You can data-bind to computed properties in templates just like a normal property. Vue is aware that vm.reversedMessage depends on vm.message, so it will update any bindings that depend on vm.reversedMessage when vm.message changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function has no side effects, which makes it easier to test and understand.

Computed Caching vs Methods

You may have noticed we can achieve the same result by invoking a method in the expression:

  1. <p>Reversed message: "{{ reverseMessage() }}"</p>
  1. // in component
  2. methods: {
  3. reverseMessage() {
  4. return this.message.split('').reverse().join('')
  5. }
  6. }

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.

This also means the following computed property will never update, because Date.now() is not a reactive dependency:

  1. computed: {
  2. now() {
  3. return Date.now()
  4. }
  5. }

In comparison, a method invocation will always run the function whenever a re-render happens.

Why do we need caching? Imagine we have an expensive computed property list, which requires looping through a huge array and doing a lot of computations. Then we may have other computed properties that in turn depend on list. Without caching, we would be executing list’s getter many more times than necessary! In cases where you do not want caching, use a method instead.

Computed Setter

Computed properties are by default getter-only, but you can also provide a setter when you need it:

  1. // ...
  2. computed: {
  3. fullName: {
  4. // getter
  5. get() {
  6. return this.firstName + ' ' + this.lastName
  7. },
  8. // setter
  9. set(newValue) {
  10. const names = newValue.split(' ')
  11. this.firstName = names[0]
  12. this.lastName = names[names.length - 1]
  13. }
  14. }
  15. }
  16. // ...

Now when you run vm.fullName = 'John Doe', the setter will be invoked and vm.firstName and vm.lastName will be updated accordingly.

Watchers

While computed properties are more appropriate in most cases, there are times when a custom watcher is necessary. That’s why Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data.

For example:

  1. <div id="watch-example">
  2. <p>
  3. Ask a yes/no question:
  4. <input v-model="question" />
  5. </p>
  6. <p>{{ answer }}</p>
  7. </div>
  1. <!-- Since there is already a rich ecosystem of ajax libraries -->
  2. <!-- and collections of general-purpose utility methods, Vue core -->
  3. <!-- is able to remain small by not reinventing them. This also -->
  4. <!-- gives you the freedom to use what you're familiar with. -->
  5. <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
  6. <script>
  7. const watchExampleVM = Vue.createApp({
  8. data() {
  9. return {
  10. question: '',
  11. answer: 'Questions usually contain a question mark. ;-)'
  12. }
  13. },
  14. watch: {
  15. // whenever question changes, this function will run
  16. question(newQuestion, oldQuestion) {
  17. if (newQuestion.indexOf('?') > -1) {
  18. this.getAnswer()
  19. }
  20. }
  21. },
  22. methods: {
  23. getAnswer() {
  24. this.answer = 'Thinking...'
  25. axios
  26. .get('https://yesno.wtf/api')
  27. .then(response => {
  28. this.answer = response.data.answer
  29. })
  30. .catch(error => {
  31. this.answer = 'Error! Could not reach the API. ' + error
  32. })
  33. }
  34. }
  35. }).mount('#watch-example')
  36. </script>

Result:

See the Pen Watch basic example by Vue (@Vue) on CodePen.

In this case, using the watch option allows us to perform an asynchronous operation (accessing an API) and sets a condition for performing this operation. None of that would be possible with a computed property.

In addition to the watch option, you can also use the imperative vm.$watch API.

Computed vs Watched Property

Vue does provide a more generic way to observe and react to data changes on a Vue instance: watch properties. When you have some data that needs to change based on some other data, it is tempting to overuse watch - especially if you are coming from an AngularJS background. However, it is often a better idea to use a computed property rather than an imperative watch callback. Consider this example:

  1. <div id="demo">{{ fullName }}</div>
  1. const vm = Vue.createApp({
  2. data() {
  3. return {
  4. firstName: 'Foo',
  5. lastName: 'Bar',
  6. fullName: 'Foo Bar'
  7. }
  8. },
  9. watch: {
  10. firstName(val) {
  11. this.fullName = val + ' ' + this.lastName
  12. },
  13. lastName(val) {
  14. this.fullName = this.firstName + ' ' + val
  15. }
  16. }
  17. }).mount('#demo')

The above code is imperative and repetitive. Compare it with a computed property version:

  1. const vm = Vue.createApp({
  2. data() {
  3. return {
  4. firstName: 'Foo',
  5. lastName: 'Bar'
  6. }
  7. },
  8. computed: {
  9. fullName() {
  10. return this.firstName + ' ' + this.lastName
  11. }
  12. }
  13. }).mount('#demo')

Much better, isn’t it?