1
votes

It appears that a vuejs computed property will only be triggered to update if it is actually bound in the template or view. Is this correct?

The reason I ask is because I'm trying to use a computed as a watcher for a prop that is passed to my component, but I don't actually want to display anything from the computed. I just want the computed to update another data item when the prop changes. If the computed requires a binding to actually work, I think I'm better off using a watch in this case.

1

1 Answers

1
votes

Computed properties are evaluated lazily, so the function you provide won't be called until something tries to read the value of the property.

If dependencies change then the value is marked as dirty but it won't be recalculated immediately. Again, that only happens if the value is accessed.

You can force the calculation of a computed property just by reading its value. Adding a watch for it will also ensure that it is always evaluated as the watcher needs to know as soon as the value changes.

Using a watch instead of a computed property might be a better way to go in the scenario you've described but it can be very convenient to abuse a computed property to get the automatic dependency tracking. It looks like this will be exposed more directly in Vue 3 so that such workarounds aren't required.