Several Events
Each line of the order has the buttons −, + and Remove now. They change the order, so they'll emit events, and App.vue will make the changes. A component can emit as many kinds of events as it needs, and lists them all in defineEmits:
const emit = defineEmits(["change-count", "remove"]);The parent listens to each of them, with a handler of its own:
<OrderList :order="order" @change-count="changeCount" @remove="removeItem" />An event can carry more than one value. emit('change-count', item.id, 1) sends two, and the handler gets them as two arguments, in the same order:
function changeCount(id, change) {
// id is the item's id, change is 1 or -1
}How to name events:
- After what happened or what the component asks for, in its own words:
order,remove,change-count. The component doesn't know how the parent removes an item, and it doesn't need to: it saysremove, andApp.vuedecides what to do. - A name of several words is written in lowercase, with hyphens between the words:
change-count, the same inemit()and after@. This way of writing is called kebab-case, as the words look like pieces of meat on a skewer.
To remove an item, App.vue replaces order.value with a new array from filter, as you know from State and Events.
Instructions
- 1
The Remove button removes its line from the order. In
OrderList.vue, emitremovewith the item'sid. InApp.vue, handle it with a functionremoveItem(id). - 2
The − and + buttons emit
change-countwith the item'sidand-1or1. InApp.vue,changeCount(id, change)adds the change to the item's count. When the count drops to 0, the item leaves the order.