Menu
CoddyTech

Adding List Items

Part of the Fundamentals section of Coddy's Vue journey. Lesson 26 of 55.

A ref can hold an array. Push a new object into its current value to add a row. This handler trims the draft, rejects blank text and creates a stable id before clearing the field.

const books = ref([]);
const draft = ref('');
let nextId = 1;
function addBook() {
  const title = draft.value.trim();
  if (!title) return;
  books.value.push({ id: nextId++, title });
  draft.value = '';
}

Validation belongs before the mutation, so a rejected draft leaves existing records untouched. An increasing id distinguishes records even when their labels are similar. Do not use the current array length as a permanent id when later deletions could cause that id to be reused.

challenge icon

Challenge

Medium

Start with the supplied supplies. Bind #draft to a text ref. Button #add appends one trimmed nonempty name as a new object with a unique id and done: false, then clears the field. Ignore whitespace-only input. Render names in ul#result with one keyed li per item and :data-id="item.id".

Use an increasing integer id counter starting at 3. Increment it only after accepting a new record.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals