Properly handling undefined computed property in the template

Hi,
I’ve been using Vue for a while, but there’s this one thing that I am always not sure how to handle properly and now I decided it’s time to ask about some rules of thumb.

Say, I have a computed property that is rather expensive to calculate (queries to database and some additional computation), so I’d rather make sure to minimize the number of times it gets evaluated. However, there may be some specific case, where the entries are not present in the DB, in which case the computed property would evaluate to undefined.

Now the question is how to handle this properly in the template.

So if I had something like this in my template:
{{ myComputedProperty.name }}

it would work most of the time, but it would crash the webpage in those cases the property evaluates to undefined.

So in such cases I usually do something like (just an example so that it’s easily understandable):
{{ myComputedProperty? myComputedProperty.name : "N/A" }}

However, I am not sure if this is a good solution, especially, I am not sure:

  1. How many times would this computed property be evaluated. In theory just when it changes, right? So it’s not like having it twice in the template like this would mean more calculation, right?
  2. Is this really safe? Will such an expression never crash the webpage as a result of eventual undefined value? This may be a dumb question, it’s just that I am not sure if recalculating the computed property can somehow trigger in between the condition and the “then” template branch. Well, most likely it can’t, but I’d like to clear that out.

Also if there’s even a better solution to this kind of problem, I’d be interested of course to know…

Cheers
Aros

Computed properties are computed the first time it’s accessed, and when that happens Vue will also notice which reactive dependencies it currently has, and it will only re-compute the computed property when one of those reactive dependencies changes. So you can access it as many times you want in between without problem.

Yes, it’s safe. JS is single threaded, and unexpected things can’t happen in the background as long as your code is running (when an asynchronous operation has completed it’s put at the end of the event queue, and it will run after your own code has finished running). As far as I know, Vue respect this.

There is no problem, but using optional chaining and the nullish coalescing operator, {{ myComputedProperty? myComputedProperty.name : "N/A" }} can be written as {{ myComputedProperty?.name ?? "N/A" }}.

1 Like