An Empty List
An empty list shows nothing, and an empty page looks broken. So when a list is empty, say so: put v-if on a message and v-else on the list:
<p v-if="order.length === 0">Your order is empty. Pick something from the menu!</p>
<ul v-else>
<li v-for="item in order" :key="item.id">{{ item.name }}</li>
</ul>Whenever the order becomes empty, the message takes the list's place, and when something is added, the list comes back.
To remove one item, a button in each li can pass its item's index to a handler, which removes the item with splice(), as in the lesson State and Events:
function removeItem(index) {
order.value.splice(index, 1);
}<li v-for="(item, index) in order" :key="item.id">
{{ item.name }}
<button @click="removeItem(index)">Remove</button>
</li>Each button calls removeItem() with the index of its own item, and Vue removes that item's element. As an argument, the index is fine: it's the item's position at the moment of the click, which is just what splice() needs. As a key, it would still be wrong.
Instructions
- 1
Give each item a button Remove, which removes the item from the order. Write a function
removeItem(index)for it. - 2
When the order is empty, show
<p class="empty">Your order is empty.</p>instead of the list.