Skip to main content

Web frameworks · Beginner · 20 min

Build your first Vue 3.5 app with the Composition API

By Padding · Updated 18 Nov 2026
node:26 image · Node.js 26.13 · Vue 3.5.45 · create-vue 3.24 · Vite 8.3

You will scaffold a Vue 3.5 and TypeScript project with create-vue, build a reading-list app with ref, computed, v-model, v-for, v-if, props and emitted events, then build it for production and check the result with vite preview.

On this page

Vue is a JavaScript framework for building user interfaces from components. Each component lives in a single-file component, a .vue file that holds its logic, its HTML template and its CSS together. The Composition API is the way you write that logic in Vue 3: you create reactive values with functions such as ref and computed, and the template updates whenever they change.

In this tutorial you build a reading list. First you put everything in one component so you can see each idea on its own: reactive state, a derived value, a form bound to state, a list and an empty state. Then you split it into two child components and connect them with props and events, which is how larger Vue apps are put together. At the end you build the app and serve the production files.

You need Node.js 26 from the Node.js install tutorial. The commands work the same on Linux and macOS.

Step 1 · Create the project

create-vue is the official scaffolding tool, and npm create vue runs it. The --ts flag adds TypeScript, and --bare leaves out the demo components so you start from an almost empty app. Passing a folder name and a flag also skips the interactive questions:

Bash
cd ~
npm create vue@3.24 reading-list -- --ts --bare
cd reading-list
npm install

The double dash passes the flags to create-vue and not to npm. Pinning @3.24 means you get the same template as this tutorial even after newer versions come out.

Check it worked

The scaffolding command ends with Done. Now run:. Look at what it made:

Bash
ls
cat package.json

You see index.html, package.json, vite.config.ts, env.d.ts, src/, public/ and three tsconfig files. In package.json, vue is the only entry under dependencies, at version 3.5. Under devDependencies you find vite, @vitejs/plugin-vue, typescript and vue-tsc. The scripts include dev, build, preview and type-check.

Vue 3.6, which adds the optional Vapor compilation mode, was still a release candidate when this tutorial was checked, so create-vue installs 3.5. Nothing in this tutorial depends on Vapor mode, and the APIs used here are unchanged in the 3.6 release candidate. create-vue 3.24 also has an experimental --vue-rc option that installs the 3.6 release candidate instead; leave it out here so your project matches the tutorial.

Step 2 · Run the dev server and read a component

Start the development server. It keeps running in this terminal, so open a second terminal in the same folder (cd ~/reading-list) for the rest of the tutorial:

Bash
npm run dev

The server prints VITE v8. followed by a version and Local: http://localhost:5173/. Open that address in a browser and you see a heading that says You did it!. From the second terminal, look at the page and the component that draws it:

Bash
curl -s http://localhost:5173/ | grep -o '<div id="app"></div>'
cat src/main.ts src/App.vue

Check it worked

curl prints <div id="app"></div>, the empty element Vue fills in. src/main.ts is three lines: it imports createApp and App.vue, and mounts the app on #app.

src/App.vue is a single-file component with three blocks:

  • <script setup lang="ts"> holds the component's logic in TypeScript. Anything you declare at the top level here, such as a variable or a function, is available to the template.
  • <template> holds the HTML the component renders. Inside it, {{ }} prints a value as text.
  • <style scoped> holds CSS that applies to this component only. Vue adds a unique attribute to the component's elements and rewrites the selectors to match it, so a rule for li here does not touch a list somewhere else.

If you work on a remote server, the dev server only listens on localhost. Forward port 5173 over SSH, or run npm run dev -- --host on a trusted network only, because the dev server is not meant to face the internet.

Step 3 · Hold state with ref and computed

Create a type for a book, then replace App.vue with a version that keeps a list of books in state. This first version does everything in one component:

Bash
cat > src/types.ts <<'TS'
export type Book = {
  id: number
  title: string
  author: string
  read: boolean
}
TS
cat > src/App.vue <<'VUE'
<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Book } from './types'

const books = ref<Book[]>([
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe', read: true },
  { id: 2, title: 'Purple Hibiscus', author: 'Chimamanda Ngozi Adichie', read: false },
])
const title = ref('')
const author = ref('')
let nextId = 3

const unread = computed(() => books.value.filter((book) => !book.read).length)

function addBook() {
  const cleanTitle = title.value.trim()
  if (cleanTitle === '') return
  books.value.push({ id: nextId++, title: cleanTitle, author: author.value.trim(), read: false })
  title.value = ''
  author.value = ''
}

function removeBook(id: number) {
  books.value = books.value.filter((book) => book.id !== id)
}
</script>

<template>
  <main class="reading-list">
    <h1>Reading list</h1>
    <p class="summary">{{ unread }} of {{ books.length }} still to read</p>

    <ul v-if="books.length > 0">
      <li v-for="book in books" :key="book.id">
        <label :class="{ read: book.read }">
          <input type="checkbox" v-model="book.read" />
          {{ book.title }}
          <span v-if="book.author" class="author">by {{ book.author }}</span>
        </label>
        <button type="button" :aria-label="'Remove ' + book.title" @click="removeBook(book.id)">
          Remove
        </button>
      </li>
    </ul>
    <p v-else class="empty">Your list is empty. Add a book below.</p>

    <form @submit.prevent="addBook">
      <label for="book-title">Title</label>
      <input id="book-title" v-model="title" />
      <label for="book-author">Author</label>
      <input id="book-author" v-model="author" />
      <button type="submit">Add book</button>
    </form>
  </main>
</template>

<style scoped>
.reading-list {
  max-width: 32rem;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: system-ui, sans-serif;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  gap: 0.5rem;
  padding: 0.4rem 0;
}

.read {
  text-decoration: line-through;
  opacity: 0.6;
}

.author {
  color: #6a707b;
}

form {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 1rem;
}
</style>
VUE

What each part does:

  • ref wraps a value so Vue can track it. In the script you read and write it through .value, as in title.value = ''. In the template Vue unwraps it for you, so you write books.length, not books.value.length.
  • computed derives a value from other reactive values. unread recounts only when books changes, and Vue caches the result between renders. Use it for anything you can work out from existing state instead of storing a second copy that can drift.
  • nextId is a plain variable. Nothing on the page shows it, so it does not need to be reactive.
  • v-model keeps an input and a ref in step both ways. On a text box it binds a string; on a checkbox it binds true or false, so ticking a box writes straight into book.read.
  • v-for="book in books" repeats the <li> for each book, and :key="book.id" gives each row a stable identity so Vue updates the right one when the list changes. Use an ID from your data, not the position in the array.
  • v-if and v-else swap the list for a message when there are no books. Unlike v-show, which only hides an element with CSS, v-if removes it from the page.
  • Each text box has a visible <label> whose for matches the input's id. The label stays on screen while you type, unlike a placeholder, and clicking it puts the cursor in the box. Screen readers read it out as the field's name.
  • @submit.prevent runs addBook and stops the browser from reloading the page, and the colon in :class and :aria-label means "this attribute is a JavaScript expression".

{{ }} always prints text, never HTML, so a title such as <b>Hi</b> shows the angle brackets instead of making bold text. That protects you from injected markup. Avoid v-html with anything a user typed.

Check it worked

The browser tab updates without a reload when you save. You see two books, Things Fall Apart crossed out, and 1 of 2 still to read. Tick Purple Hibiscus and the summary changes to 0 of 2. Add a book and it appears at the bottom with the boxes cleared. Titles in any script work, including Yoruba, Igbo or Amharic text with tone marks, because Vue passes the characters through untouched. Remove every book and the empty message appears.

Then run the type check from the second terminal:

Bash
npm run type-check

It runs vue-tsc --build and prints nothing else when the types are right. Change read: false to read: 'no' in addBook, run it again, and it reports the file and line; change it back afterwards.

Step 4 · Split the app into components with props and events

One large component gets hard to read. Move each row into a BookItem component and the form into a BookForm component. Data goes down to a child through props, and the child tells its parent what happened by emitting an event. The parent stays the only place that changes the list.

Bash
mkdir -p src/components
cat > src/components/BookItem.vue <<'VUE'
<script setup lang="ts">
import type { Book } from '../types'

defineProps<{
  book: Book
}>()

const emit = defineEmits<{
  toggle: [id: number]
  remove: [id: number]
}>()
</script>

<template>
  <li class="book-item">
    <label :class="{ read: book.read }">
      <input type="checkbox" :checked="book.read" @change="emit('toggle', book.id)" />
      {{ book.title }}
      <span v-if="book.author" class="author">by {{ book.author }}</span>
    </label>
    <button type="button" :aria-label="'Remove ' + book.title" @click="emit('remove', book.id)">
      Remove
    </button>
  </li>
</template>

<style scoped>
.book-item {
  display: flex;
  justify-content: space-between;
  gap: 0.5rem;
  padding: 0.4rem 0;
}

.read {
  text-decoration: line-through;
  opacity: 0.6;
}

.author {
  color: #6a707b;
}
</style>
VUE
cat > src/components/BookForm.vue <<'VUE'
<script setup lang="ts">
import { ref, computed } from 'vue'

const emit = defineEmits<{
  add: [title: string, author: string]
}>()

const title = ref('')
const author = ref('')
const canAdd = computed(() => title.value.trim() !== '')

function submit() {
  if (!canAdd.value) return
  emit('add', title.value.trim(), author.value.trim())
  title.value = ''
  author.value = ''
}
</script>

<template>
  <form class="book-form" @submit.prevent="submit">
    <label for="book-title">Title</label>
    <input id="book-title" v-model="title" />
    <label for="book-author">Author</label>
    <input id="book-author" v-model="author" />
    <button type="submit" :disabled="!canAdd">Add book</button>
  </form>
</template>

<style scoped>
.book-form {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 1rem;
}
</style>
VUE
cat > src/App.vue <<'VUE'
<script setup lang="ts">
import { ref, computed } from 'vue'
import BookForm from './components/BookForm.vue'
import BookItem from './components/BookItem.vue'
import type { Book } from './types'

const books = ref<Book[]>([
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe', read: true },
  { id: 2, title: 'Purple Hibiscus', author: 'Chimamanda Ngozi Adichie', read: false },
])
let nextId = 3

const unread = computed(() => books.value.filter((book) => !book.read).length)

function addBook(title: string, author: string) {
  books.value.push({ id: nextId++, title, author, read: false })
}

function toggleBook(id: number) {
  const book = books.value.find((b) => b.id === id)
  if (book) book.read = !book.read
}

function removeBook(id: number) {
  books.value = books.value.filter((book) => book.id !== id)
}
</script>

<template>
  <main class="reading-list">
    <h1>Reading list</h1>
    <p class="summary">{{ unread }} of {{ books.length }} still to read</p>

    <ul v-if="books.length > 0">
      <BookItem
        v-for="book in books"
        :key="book.id"
        :book="book"
        @toggle="toggleBook"
        @remove="removeBook"
      />
    </ul>
    <p v-else class="empty">Your list is empty. Add a book below.</p>

    <BookForm @add="addBook" />
  </main>
</template>

<style scoped>
.reading-list {
  max-width: 32rem;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: system-ui, sans-serif;
}

ul {
  list-style: none;
  padding: 0;
}
</style>
VUE

The new pieces:

  • defineProps<{ book: Book }>() declares what BookItem receives. The parent passes it with :book="book". In the template you use book directly.
  • Props flow one way. BookItem does not write to book.read itself; the checkbox uses :checked to show the value and emits toggle when clicked. Vue warns in development if a child tries to reassign a prop, and keeping changes in the parent means you always know where to look when the list goes wrong.
  • defineEmits lists the events a component can send and the arguments each one carries. @toggle="toggleBook" in the parent calls toggleBook with the emitted ID.
  • BookForm keeps its own title and author refs, because nothing else needs the half-typed text. It only tells the parent about a finished book. The canAdd computed value disables the button while the title is empty.
  • The form keeps the visible labels from the first version. The id values only need to be unique on the page; if you ever show BookForm twice, generate them with Vue's useId() instead.
  • defineProps and defineEmits are compiler macros. You do not import them; Vue's compiler handles them inside <script setup>.

Check it worked

The page looks the same as before, which is the point of the refactor. The difference you can see is that Add book is greyed out until you type a title. Open the browser's developer tools and the elements panel shows the same <ul> and <li> structure, now produced by BookItem.

Run the type check again:

Bash
npm run type-check

It passes. If you pass the wrong thing to a component, such as :book="book.title", it reports that a string is not a Book.

Step 5 · Build for production and preview the result

Stop the dev server with Ctrl+C in the first terminal.

Build the app. The build script runs the type check and Vite's production build side by side, and Vite writes the bundled, minified files to dist/:

Bash
npm run build
ls dist dist/assets

The output ends with a list such as dist/index.html, one .css file and one .js file under dist/assets/ with a hash in each name, then built in and a time. The JavaScript file is something like 27 kB gzipped, Vue included. A small bundle loads faster on slow connections and low-end phones, and costs less for anyone paying for mobile data by the megabyte.

Serve the build to check it. Like the dev server, it keeps running in the terminal:

Bash
npm run preview
Bash
curl -s http://localhost:4173/ | grep -o '<script[^>]*>'

Check it worked

The preview server listens on port 4173. The <script> tag that curl prints points at a hashed file in /assets/, not at /src/main.ts, which shows you are looking at the built app. Open http://localhost:4173/ in a browser and go through the same checks as before: add a book, tick it, remove them all.

Stop the preview server with Ctrl+C.

vite preview is for checking a build on your own machine. To publish the app, upload the contents of dist/ to any static host or serve the folder with a web server such as Nginx. It is plain HTML, CSS and JavaScript, so the server needs no Node.js.

Step 6 · Tidy up

The books live in memory, so they reset when you reload the page. The Pinia tutorial shows how to keep shared state in a store and save it across reloads, in a new project. You do not need this one for it, so remove it:

Bash
cd ~
rm -rf ~/reading-list

Check it worked

ls ~ no longer lists reading-list.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.