Showing Data
The template can show the variables of <script setup>: write the variable's name between double curly braces, {{ }}.
<script setup>
const cafe = "Corner Café";
const special = "Carrot Cake";
</script>
<template>
<h1>{{ cafe }}</h1>
<p>Today's special: {{ special }}</p>
</template>The page shows:
Corner Café
Today's special: Carrot CakeVue puts the variable's value in place of {{ special }}, and the text around the braces stays as it is. The spaces inside the braces aren't needed, but Vue code usually has them.
Every variable of <script setup> can be used in the template, with no other code: no querySelector() and no textContent. Numbers work too: with const price = 4;, €{{ price }} shows €4. And one variable can be shown in several places. When the café changes its special, you change one line of the script, and every place on the page shows the new one.
Typical mistakes:
- Single braces:
{ special }isn't replaced, and the page shows it as it is, braces and all. - A name that the script doesn't have, for example the typo
{{ specail }}: the page shows nothing in its place, and the console shows a warning. You'll learn to read it at the end of this lesson.
Instructions
- 1
The café has run out of carrot cake. Change the value of
specialto"Cheesecake"and click Run: the page shows the new special. - 2
Show the opening hours from a variable too. In
<script setup>, create a variablehourswith the text"7 am to 7 pm". Under the special, add a paragraph that showsOpen 7 am to 7 pm, with{{ hours }}in place of the time.