Computed or Function?

In Conditions and Lists, a function that the template calls did what shownMenu did in the previous exercise. Both show the same list, so why a computed value? There are two reasons.

The first is that it reads better. v-for="item in shownMenu" says what the list is: a value like any other, used without (), in the template and in other computed values.

The second is harder to see. Vue renders a component's template again whenever any data that the template shows changes, and each time, it calls the functions in the template again, even ones that have nothing to do with the change. Vue keeps a computed value, on the other hand, and works it out again only when something that it uses changes. You can see the difference with a console.log() in the function:

function sortedMenu() {
    console.log("Sorting the menu");
    return [...menu].sort((a, b) => a.price - b.price);
}

Next to the menu, this exercise's app greets the customer by name. Type a name into the field: each letter changes name, Vue renders the template again because of the greeting, and the console shows Sorting the menu again, though the menu hasn't changed at all. With six items, that doesn't matter, but with a thousand, or with work that takes long, the page would slow down while you type.

As in Conditions and Lists, the function sorts a copy, [...menu], because sort() doesn't make a new array: it reorders the one it sorts. Without the copy, menu.sort() would reorder the menu itself, and with it everything else that shows the menu.

So when the template needs a value worked out from data, make it a computed value, and keep functions for doing things, such as handlers.

Instructions

  1. Turn sortedMenu into a computed value with the same function in it, and use it in the template without (). Type a name and watch the console: Sorting the menu is there only once, from when the app started.

  2. Make the button work: when expensiveFirst is true, sortedMenu puts the most expensive items first. Click the button and watch the console: now Sorting the menu shows again, because the computed value uses expensiveFirst.