Props
Three espressos aren't much of a menu. Each MenuItem should show a different item, so the component has to get its data from its parent, the component that uses it, here App.vue. That's what props are for (short for properties): values that a parent passes to a component, written like the attributes of an HTML element:
<MenuItem name="Espresso" :price="2" />
<MenuItem name="Green Tea" :price="3" />The component says which props it takes with defineProps in its <script setup>, and uses them in its template like variables:
<script setup>
defineProps({
name: { type: String, required: true },
price: { type: Number, required: true },
});
</script>
<template>
<li class="item">
<span>{{ name }}</span>
<span class="price">€{{ price }}</span>
</li>
</template>Each prop has a name and an object that describes it:
typeis what kind of value it is:Stringfor text,Number,Booleanfortrueorfalse,ArrayorObject.required: truemeans that the parent has to pass it.defaultis the value of the prop when the parent doesn't pass it, for examplecategory: { type: String, default: "coffee" }.
Vue checks the props as the app runs, and when one is missing or has the wrong type, it says so in the console: [Vue warn]: Missing required prop: "name". And defineProps needs no import: Vue knows it in <script setup>.
Note the colon in :price="2". It's v-bind, which you know from :src: the value in the quotes is JavaScript, so :price="2" passes the number 2. Without the colon, a prop is always text. price="2" passes the text "2", and Vue warns:
[Vue warn]: Invalid prop: type check failed for prop "price". Expected Number with value 2, got String with value "2".So write text without a colon, as in name="Espresso", and anything else with one: numbers, true and false, variables.
Instructions
- 1
In
MenuItem.vue, declare two required props:name, a text, andprice, a number. Show them in place of Espresso and 2. InApp.vue, give the three items their props: Espresso for €2, Cappuccino for €3 and Green Tea for €3. The console must stay free of warnings. - 2
Add a third prop,
category: a text, not required, with the default"coffee". Show it in place of coffee, and give Green Tea the categorytea.