Arrays in Refs

A ref can hold any value: a number, text, true or false, and also an array. The café's order is a list of what the customer picked, so it's an array in a ref:

<script setup>
import { ref } from "vue";

const order = ref([]);

function addToOrder(name) {
    order.value.push(name);
}
</script>

<template>
    <button @click="addToOrder('Espresso')">Espresso</button>
    <button @click="addToOrder('Mint Tea')">Mint Tea</button>
    <p>Your order: {{ order.join(", ") }}</p>
    <p>Items: {{ order.length }}</p>
</template>

Click Espresso and then Mint Tea, and the page shows Your order: Espresso, Mint Tea and Items: 2. In the script, the array is order.value, and push() adds to it. In the template, order is the array itself, with its methods and its length.

Vue sees every change of the array, not only a new .value. All of these update the page:

  • order.value.push("Espresso") adds an item at the end.
  • order.value.pop() removes the last item.
  • order.value.splice(1, 1) removes items from anywhere in the array: the first number is the index to start at, and the second is how many items to remove. This one removes one item, the second. You'll use it in the next lesson, where every item of the order gets its own Remove button.
  • order.value = [] gives the ref a whole new array, here an empty one. That's how you use methods that make a new array and leave the old one as it was, such as filter(): order.value = order.value.filter((name) => name !== "Espresso");.

The next lesson also shows each item in an element of its own, instead of joining them into one text.

Instructions

  1. Write a function addToOrder(name) that adds the name to the end of the order, and call it from the three buttons above the order, each with its item's name.

  2. Undo removes the last item of the order. Write a function undo() for it, with pop().

  3. Start over empties the whole order: write a function startOver() that gives order.value a new, empty array.