Expressions in Braces
Between the double braces, you can write more than a variable's name. Vue accepts any JavaScript expression, that is, a piece of code that gives a value. It works the expression out and shows the result:
<script setup>
const name = "Cappuccino";
const price = 3;
const menu = ["Espresso", "Cappuccino", "Green Tea"];
</script>
<template>
<p>Two cups: €{{ price * 2 }}</p>
<p>{{ `${name}: €${price}` }}</p>
<p>{{ name.toUpperCase() }}</p>
<p>Drinks: {{ menu.length }}</p>
<p>{{ menu.join(", ") }}</p>
</template>The page shows:
Two cups: €6
Cappuccino: €3
CAPPUCCINO
Drinks: 3
Espresso, Cappuccino, Green TeaEverything you know from the JavaScript course works here: math, template literals, the methods of text, such as toUpperCase() and trim(), the methods of arrays, such as join() and includes(), and length. The braces show the expression's result, and the text around them stays as it is.
So the second paragraph could also be written without a template literal, as {{ name }}: €{{ price }}. Use whichever reads better.
Keep the expressions short. A long calculation makes the template hard to read; in the lesson Computed Values and Watchers, you'll learn where such calculations belong.
Instructions
- 1
A whole cake has 8 slices. Under the price of one slice, add a paragraph with the price of the whole cake,
Whole cake: €32. Work out the 32 in the braces, fromprice. - 2
Show the cake's name in the heading in capital letters, with
toUpperCase(). - 3
At the end, add a paragraph with the number of extras and their names, separated by commas:
Extras (3): Cream, Nuts, Honey. Useextras.lengthandjoin().