Your First Component
Your café app has grown in the last lessons: a heading, the menu, the order with its total, a form… All of it is in App.vue, and each new feature makes the file longer. In a file of a few hundred lines, finding the part you want to change takes a while. And some parts repeat: every item of the menu looks the same, just with another name and price.
That's why Vue apps are made of components: parts of the page, each in a .vue file of its own, with its own template, script and style. You know one already: App.vue is a component, the app's main one. Here's another, MenuItem.vue, which is one item of the menu:
<template>
<li class="item">
<span>Espresso</span>
<span class="price">€2</span>
</li>
</template>
<style scoped>
.item {
display: flex;
background: white;
}
</style>It has no <script setup>, because it doesn't need any variables yet. Its <style scoped> styles only the component's own elements: an element with the class item somewhere else in the app doesn't get this style.
To use the component, App.vue imports it in its <script setup> and puts it into its template, as if it were an HTML element:
<script setup>
import MenuItem from "./MenuItem.vue";
</script>
<template>
<h1>Corner Café</h1>
<ul class="menu">
<MenuItem />
<MenuItem />
</ul>
</template>import MenuItem from "./MenuItem.vue"; lets App.vue use the component under the name MenuItem. ./ means “in the same folder as this file”, and the .vue at the end is required. Without it, the red bar under the preview says App.vue(2): write the file's extension too: "./MenuItem.vue".
In the template, <MenuItem /> is replaced with the component's template. The tag closes itself with />, as there's nothing to put inside it. And you can use a component as many times as you like: this list has two items, both made by MenuItem.
With components, the exercises have more tabs: App.vue first, then the components, then the files you know, main.js, index.html and style.css.
Instructions
- 1
Move the
<li>with everything in it fromApp.vueintoMenuItem.vue: into a<template>above the<style scoped>. The espresso disappears from the page for now, becauseApp.vuedoesn't use the component yet. - 2
In
App.vue, importMenuItemand put<MenuItem />into the list, where the<li>was. The espresso is back, now with its style. - 3
Put two more
<MenuItem />into the list. The menu now has three espressos, all alike. Soon you'll give each item its own name and price.