Objects in Refs
A ref can also hold an object, which keeps things that belong together in one place. Here's an order with the customer's name and a note:
<script setup>
import { ref } from "vue";
const order = ref({
name: "Anna",
note: "",
items: ["Espresso"],
});
function addNote() {
order.value.note = "No sugar, please.";
}
</script>
<template>
<p>{{ order.name }}: {{ order.items.join(", ") }}</p>
<p>Note: {{ order.note }}</p>
<button @click="addNote">No sugar</button>
</template>In the script, order.value is the object, and order.value.note is one of its properties. Change a property, and Vue renders the page again, just as when you change .value itself. Vue sees changes deeper inside too: order.value.items.push("Mint Tea") adds to the array in the object, and the page shows it. In the template, it's order.note and order.items, without .value, as always.
In other tutorials, you may come across another function of Vue, reactive(). It makes an object reactive without a box around it, so you write order.note in the script too:
import { reactive } from "vue";
const order = reactive({ name: "Anna", note: "" });
order.note = "No sugar, please.";It works only for objects and arrays, not for numbers or text, and you can't put a new object in place of the old one. That's why this course uses ref for everything, as many Vue developers do.
Instructions
- 1
Write a function
addToOrder(name, price)that adds the name to the order'sitemsand the price to itstotal. Call it from the two buttons, for exampleaddToOrder('Cappuccino', 3). - 2
Change switches the order between for here and to go: give it a short statement that sets
toGoto the opposite.