The Parent's Data
The content of a slot is written in the parent's template, so it belongs to the parent. It can use the parent's refs, computed values and functions, as anything else in that template can. Here, a panel shows the order of App.vue, and its button calls a function of App.vue:
<script setup>
import { ref } from "vue";
import Panel from "./Panel.vue";
const order = ref(["Espresso", "Carrot Cake"]);
function clearOrder() {
order.value = [];
}
</script>
<template>
<Panel title="Your order">
<p>Items: {{ order.length }}</p>
<button @click="clearOrder">Clear</button>
</Panel>
</template>When the order changes, Vue updates the content in the panel, as it would anywhere else in the template of App.vue. The panel knows nothing about the order; it only says where its content goes. That's why one panel can be used for anything.
It doesn't work the other way round: the content can't see the panel's props and variables. A <p>{{ title }}</p> between the tags of <Panel title="Your order"> shows nothing, and the console says:
[Vue warn]: Property "title" was accessed during render but is not defined on instance.
at <Panel>
at <App>App.vue has no title. (The warning names <Panel> because that's where the content is shown.) But the parent knows the title anyway: it gave it to the panel. So it can write the title into the content itself.
The same goes for styles. The <style scoped> of Panel.vue styles the panel's own elements, its section and h2, but not the content from the parent. Style the content where it's written: in App.vue, or in style.css.
In this exercise, addToOrder() puts an item into the order with count: 1, and when the item is in the order already, it adds 1 to its count.
Instructions
- 1
In the panel Your order, show the ordered items in a list: an
lifor each item, with its name and how many were ordered, for exampleCappuccino: 2. Try the buttons Add. - 2
Under the total, add a button
Clearthat empties the order. Write its functionclearOrderinApp.vue.