Bookmarks
ReferenceFrontendVerified

Vue

Vue (Vue.js) is a framework for building interfaces from reactive components. This reference covers templates, reactivity, the Composition API, Vue Router, Pinia and Nuxt.

checked 1 Nov · next check 8 Nov · 55 min read

Sections
13
Reading
55 min
Current version
3.5.45
Written from
vuejs.org/guide/introduction.html

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Vue is and how it works

Vue is a JavaScript framework for user interfaces. You describe the interface with a template based on ordinary HTML, and the state with reactive data: when the data changes, Vue updates the affected parts of the page for you.

Vue suits both small additions to existing pages and large applications. You can add it to an existing HTML page without a build step, or embed it as web components on any page. With a build step (usually Vite), you write single-page applications (SPAs) in it, while server-side rendering (SSR) and static site generation (SSG) come from frameworks built on top of Vue, such as Nuxt. This is why the documentation calls Vue a progressive framework: you adopt it piece by piece as your needs grow.

The path from template to page runs through the compiler, a render function and the virtual DOM. The template is compiled into a render function, usually at build time, or in the browser if there is no build step. The render function returns a tree of virtual nodes (vnodes), the virtual DOM: a lightweight description of the interface in memory. Vue uses this tree to create the real DOM nodes. Rendering runs as a reactive effect: Vue tracks which data it read, and when that data changes it calls the render function again, compares the new tree with the old one and applies only the difference to the DOM.

Compilation usually happens once at build time; on each data change only the bottom three steps repeat.

The compiler knows the template ahead of time and leaves hints in the code: Vue creates the static parts of the page once and skips them when comparing during updates. This is why the documentation recommends templates, and render functions are rarely written by hand, mostly in library components with complex output logic.

Components are usually written as single-file components (SFCs), which are .vue files: logic goes in <script setup>, markup in <template> and styles in <style> (the scoped attribute limits styles to that component). Components have two API styles. In the Options API, you split logic across the data, methods and mounted options and access it through this. In the Composition API, you declare variables and functions directly in <script setup>. Both styles run on the same system; for applications with a build step, the documentation recommends the Composition API with SFCs, and this reference uses them.

How it differs from Vue Router, Pinia and Nuxt

ProjectWhat it doesWhen you need it
Vuecomponents, templates, reactivityalways: it is the core
Vue Routerofficial client-side routing: browser address → component, navigation without a page reloadin a SPA with several pages
Piniaofficial store for shared state, maintained by the Vue team; replaced Vuexwhen many components need the same data
Nuxtframework for full-stack Vue applications: file-based routes, SSR by default, a server sidewhen pages should arrive from the server as ready-made HTML

You add Vue Router and Pinia to a Vue application once it grows several pages or shared state. Choose Nuxt if a fast first screen and search indexing matter: it sends the browser ready-made HTML.

What you need to know first

  • JavaScript: modules, functions, objects, promises — see the JavaScript reference.
  • Markup and styles — see the “HTML and CSS” reference.
  • Typing components — see the TypeScript reference; the examples here are in JavaScript.

The documentation advises against starting with a framework if you do not yet know HTML, CSS and JavaScript: learn the basics first, then Vue.

Section sources

the section is written from these pages

Cheat sheet

Everyday syntax, functions and commands for <script setup>: five tables covering the template, reactivity, components, the lifecycle and terminal commands. Each row is covered in more detail in its own section of the reference.

Template

TaskHow to write it
Output a value{{ user.name }}
Bind an attribute:href="url" — same as v-bind:href
Conditional class:class="{ active: isActive }"
Style from data:style="{ fontSize: size + 'px' }"
Handle an event@click="save" — same as v-on:click
Prevent form submission@submit.prevent="onSubmit"
React to Enter@keyup.enter="search"
Show conditionallyv-if="isAdmin", then v-else-if="isGuest" and v-else
Hide without removing from the DOMv-show="isOpen"
Render a list<li v-for="item in items" :key="item.id">
Bind a field to datav-model="name"; to trim whitespace, v-model.trim="name"
Insert trusted HTMLv-html="trustedHtml" — never for user data

Reactivity

TaskHow to write it
Reactive valueconst count = ref(0), in code — count.value++
Reactive objectconst form = reactive({ email: '' })
Computed valueconst total = computed(() => price.value * qty.value)
Watch a sourcewatch(query, (value) => search(value))
Watch everything it readswatchEffect(() => console.log(count.value))
Cancel a stale request in a watcheronWatcherCleanup(() => controller.abort())
Destructure without losing reactivityconst { email } = toRefs(form)
Wait for the DOM to updateawait nextTick()

Components

TaskHow to write it
Import a componentimport TodoItem from './TodoItem.vue', in the template — <TodoItem />
Declare propsdefineProps({ title: String })
Declare eventsconst emit = defineEmits(['remove'])
Emit an eventemit('remove', id), in the parent — @remove="onRemove"
v-model on your own componentconst model = defineModel()
Named slotin the component <slot name="header" />, in the parent <template #header>
Slot types in TypeScriptdefineSlots<{ default(props: { id: number }): any }>()
Pass data down the treeprovide('theme', theme), in a descendant — inject('theme')
Element referenceconst input = useTemplateRef('input') and ref="input" in the template

Lifecycle

TaskHow to write it
Before the DOM is createdonBeforeMount(() => console.log('about to mount'))
After the DOM appearsonMounted(() => input.value.focus())
After every DOM updateonUpdated(() => console.log('updated'))
While the instance is still aliveonBeforeUnmount(() => chart.destroy())
After removal: clear a timeronUnmounted(() => clearInterval(timer))

Commands

TaskCommand
Create a projectnpm create vue@latest
Install dependencies and start the dev servernpm install, then npm run dev
Build for production into dist/npm run build
Add Pinianpm install pinia @vue/devtools-api
Create a Nuxt projectnpm create nuxt@latest my-app
Start Nuxt and open the browsernpm run dev -- -o

Section sources

the section is written from these pages

Installation and first run

The official way to start a project is npm create vue@latest, which runs create-vue, a project scaffolding tool built on Vite. After npm install and npm run dev, the app opens at http://localhost:5173.

You need Node.js 22.18 or later in the 22 line, or 24.12 or later (^22.18.0 || >=24.12.0); for how to install it, see the Node.js reference, “Installation and first run”. my-app in the commands is the project name you enter in the wizard.

bashin the terminal
npm create vue@latestcd my-appnpm installnpm run dev
textexample output (abridged)
Project name (target directory): … my-appUse TypeScript? … YesSelect features to include in your project:  JSX Support  Router (SPA development)  Pinia (state management)  Vitest (unit testing)  End-to-End Testing  Linter (error prevention)  Prettier (code formatting)...Scaffolding project in ./my-app...Done. Now run:
Wizard questionWhat it adds to the project
Use TypeScript?.ts files and tsconfig settings
JSX SupportJSX support in components
Router (SPA development)routing for a single-page application
Pinia (state management)a store for shared state
Vitest (unit testing)unit tests
End-to-End Testingbrowser tests with Playwright or Cypress
Linter (error prevention)ESLint code checking (together with Oxlint)
Prettier (code formatting)code formatting

If you are unsure, leave the list empty and answer No to the TypeScript question: you can add all of this later by hand. The example components in a new project use the Composition API and <script setup>.

Your first project

textproject without TypeScript
my-app/├── index.html      Vite entry point, contains <div id="app">├── package.json    dependencies and npm scripts├── jsconfig.json├── vite.config.js  Vite settings├── public/└── src/    ├── main.js     creates the app    ├── App.vue     root component    ├── assets/    └── components/

If you answer Yes to the TypeScript question, create-vue renames the .js files to .ts and replaces jsconfig.json with tsconfig files.

javascriptsrc/main.js
import './assets/main.css' import { createApp } from 'vue'import App from './App.vue' createApp(App).mount('#app')

createApp() creates an application instance with a root component, and .mount('#app') renders it inside the <div id="app"> from index.html; the container itself is not part of the app. Register global components (app.component()) and settings such as app.config.errorHandler before calling mount().

bashbuild for production
npm run build

This command builds the app for production into the dist/ directory.

Without a build step

For additions to existing pages, you can use Vue without a build step: with a <script> tag from a CDN, or as an ES module via <script type="module">. The .vue single-file component syntax is not available in this case.

Editor and tools

  • VS Code with the “Vue - Official” extension (formerly Volar): syntax highlighting, hints and type checking in templates. Disable the Vetur extension, which is for Vue 2, in Vue 3 projects.
  • Vue DevTools is an inspector for Vue apps: a project from create-vue already includes the Vite plugin (vite-plugin-vue-devtools), and there is also a browser extension. It shows the component tree, the state of each component, store events and profiling.
  • vue-tsc checks types in .vue files from the command line, if the project uses TypeScript.
  • eslint-plugin-vue provides ESLint rules for single-file components.

Section sources

the section is written from these pages

Templates and directives

A template is a component’s HTML markup with bindings to data: values are output with {{ }}, and behaviour is set by directives, which are attributes with the v- prefix. The template stays valid HTML, and Vue compiles it into JavaScript.

Outputting data and expressions

htmlUserCard.vue
<script setup>import { ref } from 'vue' const user = ref({ name: 'Aziza', points: 1250 })const isVip = ref(true)</script> <template>  <p>{{ user.name }}: {{ user.points + 50 }} points</p>  <p>{{ isVip ? 'VIP customer' : 'Customer' }}</p></template>

Inside {{ }} and in directive values, a single JavaScript expression works: anything you could write after return. Statements do not work: {{ var a = 1 }} and {{ if (ok) { return message } }} cause an error; use a ternary operator instead of if. Functions called in a template run on every component update, so they must not change data or make requests. Templates can access only a whitelist of common built-in globals, such as Math and Date.

Attributes, classes and styles

{{ }} does not work inside attributes; use v-bind or its shorthand :. If the value is null or undefined, Vue removes the attribute. A boolean attribute such as disabled stays as long as the value is truthy. Since Vue 3.4, when the names match you can write :id instead of :id="id".

htmltemplate
<template>  <a :href="profileUrl">Profile</a>  <button :disabled="isSaving">Save</button>   <!-- object: the class is present while the value is truthy -->  <li :class="{ active: isActive, done: todo.done }">{{ todo.text }}</li>  <!-- array: several classes at once -->  <div :class="[sizeClass, { error: hasError }]"></div>  <p :style="{ fontSize: size + 'px' }">Text</p>   <!-- all attributes from an object -->  <input v-bind="inputAttrs" /></template>

Conditions: v-if and v-show

htmltemplate
<template>  <p v-if="status === 'loading'">Loading…</p>  <p v-else-if="status === 'error'">Failed to load</p>  <OrderList v-else :orders="orders" />   <aside v-show="isFilterOpen">Filters</aside></template>

Put v-else and v-else-if immediately after an element with v-if or v-else-if, otherwise Vue does not recognise them. To toggle several elements at once, put v-if on a <template> element: that tag does not appear in the final markup.

Aspectv-ifv-show
Element when the condition is falsenot created; listeners and child components are destroyedstays in the DOM, hidden via display
Initial render when the condition is falserenders nothingalways renders
Costmore expensive to togglemore expensive on first render
<template> and v-elsesupportednot supported
When to choose itthe condition rarely changesit toggles often

Lists: v-for and key

htmltemplate
<template>  <ul>    <li v-for="(todo, index) in todos" :key="todo.id">      {{ index + 1 }}. {{ todo.text }}    </li>  </ul>   <!-- object: value and property name -->  <p v-for="(value, key) in settings" :key="key">{{ key }}: {{ value }}</p>   <!-- range: n from 1 to 5 -->  <span v-for="n in 5" :key="n">{{ n }}</span></template>

Without a key, Vue updates the list “in place”: when the data is reordered, it does not move DOM elements but rewrites their contents by position. This breaks lists where a row has its own state, such as an input field or a child component. A unique :key — a string or number, such as a record’s id — lets Vue identify elements and reorder them. An object cannot be a key, and an array index does not help: it is tied to the position, not to the record.

Do not put v-if and v-for on the same element: v-if runs first and cannot see the loop variable. To filter a list, create a computed property with the filtered array, and to hide the whole list, move v-if to the <ul>.

Vue detects methods that mutate an array, such as push(), splice() and sort(), on its own. filter(), concat() and slice() return a new array: assign it back, for example items.value = items.value.filter((item) => item.done).

Events: v-on and modifiers

htmltemplate
<template>  <!-- expression directly in the template -->  <button @click="count++">Clicked: {{ count }}</button>  <!-- the method receives the DOM event as its first argument -->  <button @click="onSave">Save</button>  <!-- your own argument and the event via $event -->  <button @click="remove(todo.id, $event)">Delete</button>   <input @keyup.enter="search" />  <form @submit.prevent="onSubmit">    <button>Submit</button>  </form>  <button @click.once="loadMore">Show more</button></template>
ModifierWhat it does
.preventcalls event.preventDefault(): the form will not reload the page
.stopcalls event.stopPropagation()
.oncethe handler runs at most once
.selfruns only if the event came from the element itself
.enter and other key namesruns only on that key
.passiveattaches the listener with { passive: true }

Modifiers can be chained: @click.stop.prevent. On a component, v-on listens to the events that the component emits itself.

Forms: v-model

htmlProfileForm.vue
<script setup>import { ref } from 'vue' const name = ref('')const age = ref(null)const agree = ref(false)const langs = ref([])const city = ref('')</script> <template>  <input v-model.trim="name" placeholder="Name" />  <input v-model.number="age" />  <label><input type="checkbox" v-model="agree" /> I agree</label>   <!-- several checkboxes write their values to an array -->  <label><input type="checkbox" value="uz" v-model="langs" /> UZ</label>  <label><input type="checkbox" value="ru" v-model="langs" /> RU</label>   <select v-model="city">    <option disabled value="">Choose a city</option>    <option>Tashkent</option>    <option>Samarkand</option>  </select></template>

v-model picks the property and event itself: value and input for text fields and <textarea>, checked and change for checkboxes and radio buttons, value and change for <select>. It ignores the value, checked and selected attributes in the markup: set the initial value in the data. Keep an empty disabled option as the first option of a <select>: if the value matches none of the options, iOS will not let the user select the first one without it.

ModifierWhat it does
.lazyupdates the data on the change event rather than after every input
.numbercasts the input to a number with parseFloat() and keeps the string if that fails; enabled automatically for type="number"
.trimstrips whitespace from both ends

Section sources

the section is written from these pages

Reactivity: ref, computed and watch

Reactivity is the mechanism that updates the interface by itself when data changes. The main way to declare reactive state is ref(): the value lives in .value, and in a template you don’t need to write .value.

Vue tracks reads and writes. When a component renders and reads count.value, Vue remembers the render as a subscriber — this is track. When code writes a new value, Vue runs the subscribers — this is trigger. For ref, reads and writes are intercepted by the getter and setter of the .value property; for reactive(), by a Proxy. Vue defers the DOM update to the next tick, so a component re-renders once no matter how many changes were made.

This is how every ref and every property of reactive() works; computed and watchEffect use the same mechanism.

ref and reactive

htmlCounter.vue
<script setup>import { ref, reactive } from 'vue' const count = ref(0)const form = reactive({ email: '', remember: true }) function increment() {  // in code you need .value, in the template you don’t  count.value++}</script> <template>  <button @click="increment">{{ count }}</button>  <input v-model="form.email" /></template>

ref() holds a value of any type. An object inside a ref also becomes deeply reactive: Vue notices changes to nested fields and arrays. reactive() makes the object itself reactive and works only with objects, arrays, Map and Set.

reactive() has two limitations. You can’t replace the whole object: a new assignment cuts the connection to the previous reactive() object. When you destructure it or pass a property to a function, a primitive value is detached from the object and stops being reactive. That is why the documentation names ref() as the main approach.

javascriptin <script setup>
import { reactive, toRefs } from 'vue' const state = reactive({ count: 0 }) // count is a plain number, the link to state is lostlet { count } = statecount++ // toRefs turns each property into a ref linked to stateconst { count: countRef } = toRefs(state)countRef.value++// state.count is now 1console.log(state.count)

computed: derived values

computed() takes a getter function and returns a computed ref. Vue caches the result and recalculates it only when the reactive data the getter read changes. A method in a template, by contrast, runs on every render: use computed for derived values, and a method when you don’t need the cache.

htmlCitySearch.vue
<script setup>import { ref, computed } from 'vue' const query = ref('')const cities = ref(['Tashkent', 'Samarkand', 'Bukhara']) // recalculated only when query or cities changeconst found = computed(() =>  cities.value.filter((city) =>    city.toLowerCase().includes(query.value.toLowerCase())  ))</script> <template>  <input v-model="query" placeholder="City" />  <p v-for="city in found" :key="city">{{ city }}</p></template>

A getter should only compute: don’t change other data in it, make requests or touch the DOM. A computed result is read-only by default — change the source data instead. Computed can’t track anything that isn’t reactive, such as Date.now(): that value won’t update.

watch and watchEffect

Watchers run a side effect in response to a change: a request, DOM work, a write to other state. watch follows an explicitly specified source — a ref, a reactive object, a getter function or an array of them — and receives the new and old values. watchEffect runs immediately and follows everything it read during execution.

htmlUserProfile.vue
<script setup>import { ref, watch, onWatcherCleanup } from 'vue' const userId = ref(1)const user = ref(null)const error = ref(null) watch(  userId,  (id) => {    const controller = new AbortController()    fetch(`/api/users/${id}`, { signal: controller.signal })      .then((res) => res.json())      .then((data) => (user.value = data))      .catch((err) => {        if (err.name !== 'AbortError') error.value = err      })    // cancel the request if the id changes before the response    onWatcherCleanup(() => controller.abort())  },  { immediate: true })</script>

Call onWatcherCleanup() (since Vue 3.5) synchronously, before the first await: the cleanup function runs before the watcher’s next run.

OptionWhat it doesDefault
immediate: truecalls the callback right away on creationthe callback waits for the first change
deep: truefollows nested changes; since Vue 3.5 it can be a number — the traversal depthshallow; deep for a reactive object
once: truefires once (since Vue 3.4)fires on every change
flush: 'post'calls the callback after the component’s DOM updatebefore the component’s DOM update

Pass a property of a reactive object as a getter: watch(() => obj.count, (count) => console.log(count)). Calling watch(obj.count, ...) passes only a number, which can’t be watched.

watchEffect tracks only what it read before the first await. Watchers created synchronously in <script setup> stop together with the component. A watcher created asynchronously — for example, inside setTimeout — must be stopped by you, using the function returned by watch or watchEffect.

shallowRef and toRefs

shallowRef() tracks only assignment to .value, not changes inside the value. It is used to save work on large immutable structures and on data managed by a third-party library. Changes inside such a value won’t trigger updates — replace it entirely.

javascriptin <script setup>
import { shallowRef } from 'vue' const chart = shallowRef({ points: [] }) // won’t trigger an update: a field inside changeschart.value.points.push(42)// will trigger: the value is replaced entirelychart.value = { points: [...chart.value.points] }

toRefs() turns a reactive object into a plain object of refs linked to the original properties. This lets a composable return state that can be destructured without losing reactivity.

nextTick: when the DOM updates

javascriptin <script setup>
import { ref, nextTick } from 'vue' const messages = ref([]) async function addMessage(text, listEl) {  messages.value.push(text)  // the DOM is still old: wait for Vue to update it  await nextTick()  listEl.scrollTop = listEl.scrollHeight}

Section sources

the section is written from these pages

Components: props, events and slots

A component is a reusable piece of interface with its own template, logic and styles, usually a separate .vue file. Data flows from the parent to the child component through input parameters (props), and back through events.

In <script setup> you only need to import a component — after that it works like a tag. Write component names in templates in PascalCase: <TodoItem /> immediately stands out from HTML elements.

The diagram shows a typical to-do list. TodoList holds the array of tasks and passes each one to TodoItem. When the user deletes a task, TodoItem emits a remove event, and the array is changed by its owner, TodoList. App passes TodoList a title through props, and gives the theme to all descendants through provide, without passing it through TodoList.

Accent arrows are props going down, the dashed line on the right is an event going up, the dashed line on the left is provide and inject.

Props: data from the parent

htmlTodoItem.vue
<script setup>defineProps({  todo: { type: Object, required: true },  showDate: { type: Boolean, default: false }})const emit = defineEmits(['remove'])</script> <template>  <li>    {{ todo.text }}    <small v-if="showDate">{{ todo.date }}</small>    <button @click="emit('remove', todo.id)">Delete</button>  </li></template>
htmlTodoList.vue
<script setup>import { ref } from 'vue'import TodoItem from './TodoItem.vue' defineProps({ title: String }) const todos = ref([  { id: 1, text: 'Buy bread', date: '2026-11-01' },  { id: 2, text: 'Call Mum', date: '2026-11-02' }]) function remove(id) {  todos.value = todos.value.filter((todo) => todo.id !== id)}</script> <template>  <h2>{{ title }}</h2>  <ul>    <TodoItem      v-for="todo in todos"      :key="todo.id"      :todo="todo"      show-date      @remove="remove"    />  </ul></template>

Declare props with the defineProps() macro — you don’t need to import it. A declaration specifies the type (String, Number, Boolean, Object, Array), whether the prop is required, and a default value; if the requirements aren’t met, Vue warns in the browser console. Declare names in camelCase and pass them in the parent’s template in kebab-case: show-date. To pass an expression rather than a string — a number, a boolean, an object — use :, for example :count="42". A boolean prop with no value means true.

Since Vue 3.5 you can destructure props without losing reactivity and set default values right in the destructuring: const { size = 'md' } = defineProps(['size']). Pass such a prop to watch as a getter: () => size.

Data flow is one-way: when the parent updates, the child’s props are overwritten, so you can’t change a prop inside the child component — Vue warns in the console. If you need an initial value, copy the prop into your own ref; if you need a transformation, use a computed; if you need to change the parent’s data, emit an event. Technically you can change nested fields of an object from props, but then the child changes the parent’s state without the parent noticing.

Events: defineEmits and emit

A child component reports actions with events. Declare them in defineEmits() and call the resulting emit function with the event name and arguments — the parent receives the arguments in the @remove handler. Component events don’t bubble: only the direct parent hears them. For communication between distant components, the documentation recommends a shared state store — see the section “Application state: Pinia”.

htmlLoginForm.vue
<script setup>const emit = defineEmits({  // no validation  cancel: null,  // argument validation: return true or false  submit: (payload) => Boolean(payload.email)}) function onSubmit(email) {  emit('submit', { email })}</script>

Declare all events, even without validation: this way the component describes itself, and Vue won’t mistake listeners for these events for fallthrough attributes.

v-model on a component: defineModel

defineModel() (since Vue 3.4) declares a prop and an update event at once: the parent writes v-model, and the child changes the received ref like an ordinary variable. Without a name the model is called modelValue and the event update:modelValue; with a name — defineModel('count'), v-model:count and update:count.

htmlSearchInput.vue
<script setup>const query = defineModel({ type: String })</script> <template>  <input v-model="query" placeholder="Search" /></template>
htmlparent
<script setup>import { ref } from 'vue'import SearchInput from './SearchInput.vue' const search = ref('')</script> <template>  <SearchInput v-model="search" />  <p>Searching for: {{ search }}</p></template>

Be careful with default in defineModel(): if the parent doesn’t pass a value, the parent keeps undefined while the child gets the default, and the two go out of sync.

Slots: passing markup

A slot passes a piece of template into a component, not data. The component marks the place with a <slot> tag, and the parent writes the content between the component’s tags. Slot content sees the parent’s data, not the child’s.

htmlBaseCard.vue
<script setup>defineProps({ total: Number })</script> <template>  <article class="card">    <header><slot name="header" /></header>    <!-- default slot; the text inside is a fallback -->    <slot>Empty</slot>    <footer><slot name="footer" :total="total" /></footer>  </article></template>
htmlparent
<template>  <BaseCard :total="3">    <template #header>      <h2>Cart</h2>    </template>     <p>Items in the cart</p>     <!-- slot props: total comes from BaseCard -->    <template #footer="{ total }">      Total: {{ total }}    </template>  </BaseCard></template>

#header is shorthand for v-slot:header. Anything not wrapped in a <template> with a slot name goes into the default slot. Attributes on <slot> become slot props (a scoped slot): the parent receives them in v-slot and can destructure them. If a component has both named slots and props on the default slot, wrap the default slot in <template #default> too, or the template won’t compile. In TypeScript, slot types are set with defineSlots().

Fallthrough attributes

Attributes and listeners that the parent passed but the component didn’t declare in props and emits are treated by Vue as fallthrough attributes: for a component with a single root element they land on that root, for example class and event listeners. In the template they are available as $attrs, and in <script setup> through useAttrs(). Inheritance is disabled with defineOptions({ inheritAttrs: false }).

provide and inject: data for deep descendants

When data is needed by a deeply nested component, passing props through every level is tedious — this is called prop drilling. provide() in an ancestor makes a value available to all descendants, and inject() in a descendant gets it by key, however many levels lie between them. If several ancestors provide the same key, the nearest one wins.

htmlApp.vue
<script setup>import { ref, provide } from 'vue' const theme = ref('light') function toggleTheme() {  theme.value = theme.value === 'light' ? 'dark' : 'light'} // the ref is passed as is and stays reactiveprovide('theme', { theme, toggleTheme })</script>
htmlThemeToggle.vue
<script setup>import { inject } from 'vue' // the second argument is the default valueconst { theme, toggleTheme } = inject('theme', {  theme: 'light',  toggleTheme: () => {}})</script> <template>  <button :class="theme" @click="toggleTheme">Theme</button></template>

Change provided state in the ancestor, and give descendants a function to change it: this keeps the data and its changes in one place. Without a default value, inject() warns if nobody provided the key. An app-wide value is set with app.provide().

A component with a top-level await in <script setup> becomes asynchronous and must run inside <Suspense>, which is still experimental.

Section sources

the section is written from these pages

Composition API: lifecycle and composables

Code in <script setup> runs once, when the component instance is created. Lifecycle hooks, such as onMounted(), register functions for later stages, and repeated stateful logic is extracted into a composable — a useX() function that returns refs.

Every instance goes through the same stages: state setup, DOM creation, updates when data changes, and removal. Register hooks synchronously during setup: inside setTimeout, Vue no longer knows which component to attach them to. You can also call a hook in an external function, as long as it is called synchronously from <script setup>.

The update cycle repeats any number of times while the component is on the page. During SSR, none of these hooks is called.
  1. <script setup> creates state, computed properties and watchers; there is no DOM yet.
  2. onBeforeMount — the state is ready, but the DOM has not been created.
  3. onMounted — the DOM of the component and its synchronous child components has been created and inserted into the container.
  4. On a data change: onBeforeUpdate — the DOM is still old, onUpdated — the DOM has been updated. This cycle repeats.
  5. onBeforeUnmount — the component is about to be removed, but the instance is still fully working.
  6. onUnmounted — child components have been removed, and the render, computed properties and watchers are stopped.
HookWhat to do in it
onMountedaccess the DOM, attach libraries to elements; keep code that is needed only in the browser
onBeforeUpdateread the DOM before the update; changing state here is allowed
onUpdatedread the updated DOM. Don’t change state here — you will get an infinite update loop. To wait for the DOM after a specific change, use nextTick()
onUnmountedclean up timers, DOM event listeners and server connections
onBeforeMount, onBeforeUnmountrare cases: before the first render and while the instance is still working

With server-side rendering these hooks are not called, so keep browser-only code in onMounted.

Element references: useTemplateRef

htmlSearchBox.vue
<script setup>import { useTemplateRef, onMounted } from 'vue' // the argument matches the value of the ref attributeconst input = useTemplateRef('search-input') onMounted(() => {  input.value.focus()})</script> <template>  <input ref="search-input" /></template>

useTemplateRef() appeared in Vue 3.5; before that you declared ref(null) with the same name as the ref attribute. The element is available only after mounting: on the first render the value is null, so check it in watchEffect. On a child component, ref gives its instance, but a component using <script setup> is closed: from outside you see only what it exposed with the defineExpose() macro.

Composables: your own logic in a function

A composable is a function that uses the Composition API to hold and reuse stateful logic. Inside it you can create refs, computed properties, watchers and hooks — they attach to the component that called the function. Every call creates its own state, so components don’t interfere with each other.

javascriptsrc/composables/mouse.js
import { ref, onMounted, onUnmounted } from 'vue' export function useMouse() {  const x = ref(0)  const y = ref(0)   function update(event) {    x.value = event.pageX    y.value = event.pageY  }   // the listener is removed together with the component  onMounted(() => window.addEventListener('mousemove', update))  onUnmounted(() => window.removeEventListener('mousemove', update))   return { x, y }}
htmlMouseDemo.vue component
<script setup>import { useMouse } from './composables/mouse.js' const { x, y } = useMouse()</script> <template>Cursor: {{ x }}, {{ y }}</template>

For a composable to react to changes in an argument, accept a ref or a getter and read it with toValue() inside watchEffect:

javascriptsrc/composables/fetch.js
import { ref, watchEffect, toValue } from 'vue' export function useFetch(url) {  const data = ref(null)  const error = ref(null)   watchEffect(() => {    data.value = null    error.value = null    // toValue accepts a string, a ref or a getter    fetch(toValue(url))      .then((res) => res.json())      .then((json) => (data.value = json))      .catch((err) => (error.value = err))  })   return { data, error }}

Calling useFetch(() => '/api/posts/' + id) with a reactive id loads the data again each time it changes, while a plain string triggers a single load.

  • Name it in camelCase with the use prefix.
  • Return a plain object of refs, not reactive(): such a result can be destructured without losing reactivity.
  • Start DOM side effects in onMounted() and clean them up in onUnmounted().
  • Call a composable synchronously in <script setup> or setup(); after an await, only in <script setup>.

Composition API and Options API

The Options API arranges code into the data, methods and mounted options, so the logic for one task ends up in different places in the file. In the Composition API you keep it together and extract it into composables. The Composition API infers TypeScript types better and gives smaller production code. The Options API is not deprecated and remains a good choice for simple components, but in large projects the Composition API scales better — which is why this reference uses it.

Mixins for reusing logic are no longer recommended in Vue 3: use composables instead.

Section sources

the section is written from these pages

Routing: Vue Router

Vue Router is the official client-side routing library: it links the browser address to a component and changes the page without a reload. Routes are described by a routes array, and <RouterView> renders the current page.

The router matches a path to a component, <RouterView> shows the component of the current route, and <RouterLink> creates a link that Vue Router follows without a reload. For a ready-made example, choose Vue Router in the npm create vue@latest wizard.

javascriptsrc/router/index.js
import { createRouter, createWebHistory } from 'vue-router'import HomeView from '../views/HomeView.vue' export const router = createRouter({  history: createWebHistory(),  routes: [    { path: '/', name: 'home', component: HomeView },    {      path: '/users/:id',      name: 'user',      component: () => import('../views/UserView.vue')    },    {      path: '/login',      name: 'login',      component: () => import('../views/LoginView.vue')    },    {      path: '/account',      component: () => import('../views/AccountView.vue'),      meta: { requiresAuth: true }    },    // any other address is a 404 page    {      path: '/:pathMatch(.*)*',      name: 'not-found',      component: () => import('../views/NotFound.vue')    }  ]})
javascriptsrc/main.js
import { createApp } from 'vue'import App from './App.vue'import { router } from './router' // call use() before mount()createApp(App).use(router).mount('#app')
htmlApp.vue
<template>  <nav>    <RouterLink to="/">Home</RouterLink>    <RouterLink :to="{ name: 'user', params: { id: 42 } }">      Profile    </RouterLink>  </nav>  <!-- the component of the current route is rendered here -->  <RouterView /></template>

For real applications the documentation recommends createWebHistory() — HTML5 mode. createWebHashHistory() is used less often: the path goes after # and is never sent to the server, but such addresses are worse for search engines. In HTML5 mode, when the page is refreshed the server needs a fallback to index.html; how to configure nginx is described in the section “Common errors and diagnostics”.

Route parameters

A segment with a colon is a parameter: the path /users/:id matches both /users/7 and /users/aziz. The values are in route.params, with route.query and route.hash alongside. In <script setup>, useRoute() returns the current route and useRouter() returns the router itself.

htmlsrc/views/UserView.vue
<script setup>import { ref, watch } from 'vue'import { useRoute, useRouter } from 'vue-router' const route = useRoute()const router = useRouter()const user = ref(null) // the component isn’t recreated when :id changes,// so we watch the parameterwatch(  () => route.params.id,  async (id) => {    const res = await fetch(`/api/users/${id}`)    user.value = await res.json()  },  { immediate: true }) function goHome() {  router.push({ name: 'home' })}</script> <template>  <h1 v-if="user">{{ user.name }}</h1>  <button @click="goHome">Go home</button></template>

When navigating from /users/7 to /users/8, Vue Router doesn’t recreate the component but reuses it, and some lifecycle hooks are not called. So watch the parameter with watch or with the navigation guard onBeforeRouteUpdate(). To navigate programmatically, use router.push(): router.push('/about') or router.push({ name: 'home' }). The path /:pathMatch(.*)* matches any address and puts it in route.params.pathMatch — this is how you build a 404 page.

Redirects

An old address leads to a new one through the redirect option — such a route needs no component, because it is never displayed. The value is a path, a route object or a function; navigation guards apply to the redirect target, not to the route itself.

javascriptsrc/router/index.js
const routes = [  { path: '/home', redirect: '/' },  {    // /search/screens → /search?q=screens    path: '/search/:searchText',    redirect: (to) => ({      path: '/search',      query: { q: to.params.searchText }    })  }]

Nested routes

If part of a page changes inside a shared layout, use nested routes: the parent’s component has its own <RouterView>, and the route has a children array. An empty path '' sets the default content, and a path that starts with / is treated as a root path.

javascriptsrc/router/index.js
const routes = [  {    path: '/users/:id',    component: UserLayout,    children: [      // /users/7      { path: '', component: UserHome },      // /users/7/posts      { path: 'posts', component: UserPosts }    ]  }]

Login check: beforeEach

Navigation guards intercept a navigation: router.beforeEach() is called before each one. The guard receives to and from and returns false to cancel the navigation or a new address to redirect; undefined and true let the navigation continue. A guard can be asynchronous.

javascriptsrc/router/index.js
import { useAuthStore } from '../stores/auth' router.beforeEach((to) => {  // get the store inside the guard, not at import time  const auth = useAuthStore()  const needsLogin = to.meta.requiresAuth && !auth.isLoggedIn  // the name check prevents an endless redirect loop  if (needsLogin && to.name !== 'login') {    return { name: 'login', query: { redirect: to.fullPath } }  }})

The third argument, next, is still supported, but it is often misused: it must be called exactly once on every execution path of the guard. Return a value instead of using next. router.afterEach() is called after the navigation and cannot affect it — use it to send analytics and change the page title.

Lazy loading pages

Set a route’s component with a function, () => import('../views/UserView.vue'): Vue Router loads it on the first visit to the page and takes it from the cache afterwards, and Vite puts the page’s code in a separate file. The documentation recommends loading all routes this way. Don’t use a Vue async component as a route component: a route needs a plain function.

File-based routes and Data Loaders

Since version 5, vue-router includes a file-based routing plugin: pages are components in src/pages (index.vue, users/[id].vue), and the plugin builds the routes array and the TypeScript types itself. For page data there are Data Loaders: a composable from defineBasicLoader() runs inside a navigation guard, and the component receives the data already loaded. Both features need setup (a plugin in vite.config.ts), and loaders are experimental; moving from Vue Router 4 without the file-based routing plugin needs no code changes, and with the plugin it follows the “Migrating to Vue Router 5” guide in the Vue Router documentation.

Section sources

the section is written from these pages

Application state: Pinia

Pinia is the official library for shared application state. A store holds data and logic that many components need, outside the component tree. The Vue team maintains it, and it is recommended over Vuex for new applications.

When you need a store

A component’s own state lives in its ref. When several components need the same data, you can lift it to a common ancestor and pass it down as props, or offer it to all descendants with provide() — see the “Components: props, events and slots” section. In a deep tree this turns into prop drilling, and the data is tied to the component tree. In a small application, a shared reactive() object in its own module is enough: every component that imports it updates together.

javascriptsrc/store.js
import { reactive } from 'vue' // one object for the whole applicationexport const store = reactive({  count: 0,  increment() {    this.count++  }})

Change such state through the store’s methods rather than directly from any component, so the change logic stays in one place. With server-side rendering, this object is shared by all requests, so one user’s data can leak to another. Pinia adds what large projects need: team conventions, Vue DevTools with a change history, hot module replacement and SSR support.

Put data in a store when it is needed in many places, such as the current user in the site header, or when it has to survive navigation between pages, such as a multi-step form. Whether an element is visible on a single page stays in the component.

Installation and your first store

bashin the project directory
npm install pinia @vue/devtools-api

Since Pinia 4, the @vue/devtools-api package is required: it is a dependency of the DevTools integration, and you install it alongside pinia.

javascriptsrc/main.js
import { createApp } from 'vue'import { createPinia } from 'pinia'import App from './App.vue' const app = createApp(App)app.use(createPinia())app.mount('#app')
javascriptsrc/stores/cart.js
import { ref, computed } from 'vue'import { defineStore } from 'pinia' export const useCartStore = defineStore('cart', () => {  // ref is state, computed is getters, functions are actions  const items = ref([])  const total = computed(() =>    items.value.reduce((sum, item) => sum + item.price, 0)  )   function add(item) {    items.value.push(item)  }   async function load() {    const res = await fetch('/api/cart')    items.value = await res.json()  }   // a reset is an ordinary action with the initial values  function reset() {    items.value = []  }   return { items, total, add, load, reset }})

defineStore() takes a unique id, which Pinia uses to connect the store to DevTools, and a setup-style function: each ref becomes state, each computed becomes a getter and each function becomes an action. Return all of the state: a store has no private state, and properties you don’t return break SSR and DevTools. Name the function use…Store, for example useCartStore. There is also a second form, an object with state, getters and actions, as in the Options API.

Actions can be asynchronous: await works inside them, and an action can call another store.

Using a store in a component

htmlCartSummary.vue
<script setup>import { storeToRefs } from 'pinia'import { useCartStore } from '@/stores/cart' const cart = useCartStore()// state and getters: only through storeToRefsconst { items, total } = storeToRefs(cart)// actions can be taken directlyconst { add } = cart</script> <template>  <p>Items: {{ items.length }}, total: {{ total }}</p>  <button @click="add({ id: 3, price: 15000 })">Add</button></template>

The store is created the first time you call useCartStore(). It is an object wrapped in reactive: you don’t write .value on getters, but you can’t destructure it directly either, or the values stop updating. storeToRefs() creates a ref for each state property and getter and skips actions.

Using a store outside a component

useCartStore() looks up the active Pinia instance, so it only works after app.use(pinia). Calling it at the top level of a module, before Pinia is installed, fails with an error. Move the call into a function that runs later, such as a navigation guard, an event handler or an action.

javascriptsrc/router/index.js
router.beforeEach((to) => {  // Pinia is already installed here  const auth = useAuthStore()  if (to.meta.requiresAuth && !auth.isLoggedIn) return '/login'})

With server-side rendering, pass the Pinia instance explicitly, as in useAuthStore(pinia), so state is not mixed between application instances.

Section sources

the section is written from these pages

Nuxt and server-side rendering

With server-side rendering (SSR), the server sends ready-made HTML, and the browser then hydrates it: Vue attaches components and event handlers to the markup. Nuxt, a Vue framework with SSR by default, provides this setup out of the box.

When you need SSR

SSR shortens the time until content appears, especially on slow networks and weak devices, and gives search crawlers a ready-made page. The price is a Node.js server instead of static hosting, extra CPU load and code that has to run on both the server and the browser. An internal dashboard, where a few hundred extra milliseconds of loading don’t matter, doesn’t need SSR. If pages are the same for every user, static site generation (SSG) is simpler: the HTML is built once at build time.

Nuxt modeHow it worksWhen to choose it
Universal, the defaultthe server renders HTML on each request, the browser hydrates itcontent sites: blogs, shops, storefronts
Client-side, ssr: falseHTML is built in the browserdashboards and apps that don’t need search indexing
Static, nuxt generateall pages are rendered at build timedocumentation, blogs
Hybrid, routeRuleseach route has its own mode and cachea site with sections of different kinds

What Nuxt gives you

Nuxt takes care of what you would otherwise assemble yourself when setting up SSR by hand: two builds, one for the server and one for the browser, plus routing, data loading and stores that work in both environments. Routes are defined by files in app/pages/, components and composables are imported automatically, and the server API lives in server/api/. The Nitro server engine builds the application into the .output directory, which you run on Node.js, serverless or edge servers.

bashin a terminal
npm create nuxt@latest my-appcd my-appnpm run dev -- -o

You need Node.js 22 or later; the documentation recommends the current even-numbered LTS release. The dev server runs at http://localhost:3000, and the -o flag opens it in the browser straight away.

textNuxt 4 structure
my-app/├── nuxt.config.ts├── app/│   ├── app.vue           root component│   ├── pages/            pages: a file is a route│   │   └── users/[id].vue│   ├── components/│   └── composables/└── server/    └── api/              API handlers
typescriptserver/api/hello.ts
// handler for the /api/hello routeexport default defineEventHandler(() => ({ message: 'Hello' }))

Data fetching: useFetch and useAsyncData

If you load data with a plain $fetch in <script setup>, the request runs twice: on the server during rendering and in the browser during hydration. useFetch and useAsyncData make the request on the server and pass the result to the browser along with the page (the payload), so there is no second request.

htmlapp/pages/users/[id].vue
<script setup>const route = useRoute() // the URL is a function: the data reloads when the id changesconst { data: user, status, error } = await useFetch(  () => `/api/users/${route.params.id}`)</script> <template>  <p v-if="status === 'pending'">Loading…</p>  <p v-else-if="error">Error: {{ error.message }}</p>  <h1 v-else>{{ user.name }}</h1></template>

Pass a URL built from reactive data as a function: a string assembled in advance won’t update when that data changes. useFetch returns the refs data, status and error, plus a refresh function. With await, navigation to the page waits for the data; with the lazy: true option it doesn’t, and you show the loading state yourself.

useFetch(url) is shorthand for useAsyncData with $fetch. Use useAsyncData when there are several requests or your own function supplies the data: the first argument is a unique cache key and the second is the fetch function. Keep $fetch for user actions such as submitting a form or clicking a button.

javascriptin <script setup>
// one fetch made of two requests, under the key 'dashboard'const { data } = await useAsyncData('dashboard', async () => {  const [stats, news] = await Promise.all([    $fetch('/api/stats'),    $fetch('/api/news')  ])  return { stats, news }})

Browser-only code

With SSR, the <script setup> code runs on both the server and the browser, while onMounted and event handlers run only in the browser. Access window, document and browser-only libraries inside onMounted, and wrap markup that depends on the browser in <ClientOnly>. Don’t start timers or other effects that need cleanup in setup: unmount hooks are not called on the server, so such a timer would run forever.

htmlapp/components/Viewport.vue
<script setup>const width = ref(0) onMounted(() => {  // window exists only in the browser  width.value = window.innerWidth})</script> <template>  <p>Window width: {{ width }}</p>  <ClientOnly>    <MapWidget />  </ClientOnly></template>

Section sources

the section is written from these pages

Security

The main rule of Vue is never to use untrusted content as a component template: that is the same as letting someone else run JavaScript, and with SSR it runs on the server too. The other threats are XSS through v-html, and links and styles built from user data.

javascriptdon’t do this
// the user’s string becomes template codecreateApp({  template: `<div>${userProvidedString}</div>`}).mount('#app')
htmldo this
<template>  <!-- the string is output as escaped text -->  <div>{{ userProvidedString }}</div></template>

What Vue escapes for you

Vue escapes the content of {{ }} and the values of attribute bindings such as :title itself, using browser APIs: textContent and setAttribute. The string <script>alert(1)</script> in {{ }} is output as text, and a quote in :title won’t close the attribute: a vulnerability is possible here only if the browser itself is vulnerable.

Don’t mount a Vue application on an element that already contains server-rendered HTML with user data: text that is safe as HTML, such as {{ ... }}, will be run by Vue as a template expression.

v-html and innerHTML

v-html, the innerHTML property in a render function and JSX all insert a string as HTML without escaping. HTML from a user can’t be considered safe unless it is shown in an isolated <iframe> with sandbox, or is visible only to its own author.

htmldon’t do this
<div v-html="comment.body"></div>
htmldo this
<p>{{ comment.body }}</p>

Links from user data

:href="userUrl" escapes the value, but a javascript: URL will still run code on click. Validate and sanitise URLs on the server before saving them to the database, so that every API client, mobile ones included, is protected. Sanitising on the frontend means the problem is already there. Even a sanitised URL is no guarantee from Vue that it leads to a safe site.

Styles and handlers from data

User-supplied styles allow clickjacking: a link is stretched into a transparent block over the “Sign in” button and leads to a fake login page. A <style> tag inside a Vue template is not rendered; in :style, let the user set only individual safe properties, through an object.

htmldon’t do this
<a :href="sanitizedUrl" :style="userStyles">Profile</a>
htmldo this
<a  :href="sanitizedUrl"  :style="{ color: userColor, background: userBackground }">  Profile</a>

Don’t bind user strings to handler attributes such as onclick and onfocus, and don’t render <script> from a template: templates and render functions must have no side effects.

Server-side rendering

With SSR, the initial state of the stores is written into the page’s HTML so that the browser can pick it up during hydration. It almost always contains data that a user entered, so escape the state when you serialise it, for example with the devalue library that Nuxt uses. Running template code on the server is one more reason not to accept templates from users.

Updates, build and backend

  • Keep Vue and the official libraries up to date, as the documentation recommends; fixed vulnerabilities are listed in the “Versions and what’s new” section.
  • Serve the production build in production: create-vue and Vite set it up for you, and from a CDN use the .prod.js files. It has no warnings, no props validation and no DevTools integration.
  • CSRF and XSSI are handled by the backend: agree with its team on how to send the CSRF token with forms.
  • In production, send errors to a monitoring system through app.config.errorHandler.
  • The Vue documentation recommends reading the OWASP Cross Site Scripting Prevention Cheat Sheet; XSS as a class of vulnerability is described in the OWASP Top 10 reference, in the section “A05:2025 Injection”.
  • The Content-Security-Policy (CSP) header also helps against third-party scripts running on the page; how to choose its policy is described in the OWASP Top 10 reference, in the section “A02:2025 Security misconfiguration”.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the browser console or Vue DevTools: in development mode they show Vue’s full messages, and in a production build they show short codes. The code received by app.config.errorHandler and onErrorCaptured is decoded by the Production Error Code Reference page: for example, 1 is a render function and m is a mounted hook.

  1. Find Vue’s message in the console and the component where the error happened.
  2. If it is a production build, decode the code using the Production Error Code Reference table.
  3. Check that the change goes through a ref or the reactive object itself, not through a copy of the value.
  4. With SSR, compare the HTML that came from the server with the markup after hydration.

The data changed but the screen didn’t

Cause: the change bypassed the reactivity system. Most often this is destructuring a reactive() object, so the variable gets a copy of a primitive value, or replacing a reactive object as a whole.

javascriptwon’t update
let state = reactive({ count: 0 }) // a copy of the value: state.count won’t changelet { count } = statecount++ // a new object: the template is watching the old onestate = reactive({ count: 1 })
javascriptfix
const count = ref(0)count.value++ // or change a property without replacing the objectconst state = reactive({ count: 0 })state.count++

{{ object.id + 1 }} outputs [object Object]1

Cause: in a template, a ref is unwrapped only if it is at the top level. object.id is a ref inside a plain object, so in an expression it stays a ref object.

javascriptfix
const object = { id: ref(1) }// lift the ref to the top level: use {{ id + 1 }} in the templateconst { id } = object

The DOM is still old right after a change

Cause: Vue doesn’t update the DOM immediately but on the next tick, once for all the changes.

javascriptfix
count.value++await nextTick()// now the DOM is updated

v-model cannot be used on a prop, because local prop bindings are not writable. Use a v-bind binding combined with a v-on listener that emits update:x event instead.

Cause: a component changes its own prop through v-model, but props are read-only: only the parent changes them. The compiler error code is 44.

htmlwon’t compile
<script setup>defineProps(['title'])</script> <template>  <input v-model="title" /></template>
  • Pass the value to the parent, as the message suggests: :value="title" and the update:title event.
  • Or declare a two-way binding with defineModel('title') — see the “Components: props, events and slots” section.

List rows mix up their fields after sorting

Cause: v-for has no :key, or the key isn’t tied to the record, such as an index. Without a key, Vue updates elements in place, and their state, such as input in a field or a child component, doesn’t move along with the data.

htmlfix
<TodoItem v-for="todo in todos" :key="todo.id" :todo="todo" />

A key is a string or a number that is unique among siblings; an object can’t be a key. For <template v-for>, put the key on the <template> itself, otherwise the compiler reports <template v-for> key should be placed on the <template> tag.

A v-if inside v-for can’t see the item

Cause: on the same element, v-if runs before v-for, so the loop variable isn’t defined yet in the condition.

htmldon’t do this
<li v-for="todo in todos" v-if="!todo.done">{{ todo.text }}</li>
htmlfix
<script setup>import { computed } from 'vue' const props = defineProps(['todos'])const activeTodos = computed(() => props.todos.filter((t) => !t.done))</script> <template>  <li v-for="todo in activeTodos" :key="todo.id">{{ todo.text }}</li></template>

Hydration mismatch

Cause: the HTML from the server doesn’t match what the browser rendered. Common cases are invalid tag nesting that the browser “fixed” (a <div> inside a <p>), random values, and time in different time zones on the server and for the user. Vue tries to repair the DOM itself, but it costs performance, so remove mismatches during development.

  • Check tag nesting: a <p> can’t contain a <div>.
  • Render browser-dependent values, such as random numbers and local time, only on the client: use v-if with a flag that is set in onMounted.
  • Since Vue 3.5, the data-allow-mismatch attribute allows a mismatch that can’t be avoided.
htmlbrowser only
<script setup>import { ref, onMounted } from 'vue' const isClient = ref(false)onMounted(() => (isClient.value = true))</script> <template>  <time v-if="isClient">{{ new Date().toLocaleTimeString() }}</time></template>

404 when you refresh the page

Cause: the router uses createWebHistory(), and the server looks for a file at /users/42 and doesn’t find it. The application lives in a single index.html, and the server must serve it for any path that has no file.

nginxnginx
location / {  try_files $uri $uri/ /index.html;}

If you can’t configure the server, use createWebHashHistory(): the path comes after # and isn’t sent to the server, but such URLs are worse for search. The rest of the server setup, including compression, caching and HTTPS, is covered in the Nginx reference.

Minor template compiler errors

SymptomCauseWhat to do
v-else/v-else-if has no adjacent v-if or v-else-if.another element sits between v-if and v-elseput v-else right after the element with v-if
v-if/else branches must use unique keys.the v-if and v-else branches have the same keygive the branches different keys
Tags with side effect (<script> and <style>) are ignored in client component templates.<script> or <style> inside a templatemove the code to <script setup> and the styles to the component’s <style>
Element is missing end tag.an unclosed tagclose the tag
Interpolation end sign was not found.{{ without }}close the interpolation
v-model can only be used on <input>, <textarea> and <select> elements.v-model on a plain element such as <div>use a form field or your own component with defineModel()

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Vue 3.5. The latest release is 3.5.45, published on 5 November 2026. Vue has no fixed release cycle: patches ship as needed, and minor releases with new features usually arrive every 3–6 months, each going through a beta stage.

BranchStatusFirst releaseLatest release
3.6release candidates (RC), not for production—3.6.0-rc.14 — 30 October 2026
3.5current, receives fixes3.5.0 — 3 September 20243.5.45 — 5 November 2026
3.4no fixes released3.4.0 — 29 December 20233.4.38 — 15 August 2024
2.7support ended on 31 December 20232.7.0 — 1 July 20222.7.16 — 24 December 2023, the final Vue 2 release

Current branches of the main ecosystem packages:

PackageVersionPurpose
vue-router5.4routing — see the section “Routing: Vue Router”
pinia4.1shared state — see the section “Application state: Pinia”
nuxt4.6a framework built on Vue — see the section “Nuxt and server-side rendering”

Pre-releases (alpha, beta and RC) exist for testing and feedback. They may contain breaking changes, so do not install them in production, and pin the exact version. TypeScript type definitions can also change in breaking ways between minor versions, so for TypeScript projects the documentation advises pinning the minor version in a semver range and upgrading it manually.

What changed in 3.5

  • Reactivity: the reactivity system was rewritten around version counting and doubly linked lists, and array tracking is faster; the deep option of watch accepts a number — the traversal depth.
  • Reactivity: onWatcherCleanup() registers cleanup inside a watcher; watchers and effects gain pause() and resume().
  • Components: destructuring of defineProps() is reactive by default.
  • Composition API: useTemplateRef() for element references; useId() and app.config.idPrefix for unique ids.
  • Nuxt and server-side rendering: lazy hydration strategies for async components and the data-allow-mismatch attribute for unavoidable mismatches.
  • Security: Trusted Types compatibility.

Deprecated and removed

  • Vue 2 has been unsupported since 31 December 2023: no new features and no fixes. The final release is 2.7.16; start new projects on Vue 3.
  • Deprecated features keep working and are removed only in the next major release; replacements are announced in minor releases.
  • Vue Router 5 is a transitional release before version 6, which will be ESM-only and remove deprecated APIs; upgrading from Router 4 is covered in the section “Routing: Vue Router”.
  • The deprecated compiler option parseExpressions was removed in 3.5.
  • What to use instead of Vuex is covered in the section “Application state: Pinia”.

Security updates

IdentifierWhat is affectedFixed in
GHSA-g2v6-rqmx-r4w6@vue/server-renderer: XSS during SSR when v-bind receives an object whose keys come from user data — a carriage return character in an attribute name. Severity is high; versions up to and including 3.5.41 are affected3.5.42

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Vue” topic
13 sections
Another reference · Backend

HTTP and REST

Verified 1 Nov
All references · 61