Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 87 ยท Testing and Debugging

Debugging Vue

Debug Vue apps: read dev warnings, use Vue DevTools, know dev versus production builds, catch errors with errorHandler and decode common messages.

Every Vue developer spends a good part of the day staring at something that does not behave. The good news is that Vue is unusually helpful when it breaks. In development it prints clear warnings that name the component and the problem, it ships with a browser extension that shows live state, and it gives you hooks to catch errors in one place. The skill is knowing where to look first.

This lesson covers the debugging toolbox in the order you will reach for it: the console, Vue DevTools, the difference between development and production builds, central error handling with app.config.errorHandler and onErrorCaptured, and a catalog of the messages you will meet most often. Plain JavaScript techniques apply too; see JavaScript error handling for the basics.

Start with the console

When something is wrong, open the browser console before you touch any code. Vue prints warnings that begin with [Vue warn], and each one names the component and shows a component trace: the chain of parents leading to the problem. Most bugs in a template are explained right there.

These warnings exist only in development builds. The build you ship to users has them stripped out, which makes it smaller and faster. That has two consequences:

  • Always debug in the dev build (npm run dev with Vite). If you debug the production bundle, Vue will be silent, and you will wonder why.
  • Do not rely on a warning as part of your logic. In production it never appears.

On this site the live examples load Vue's production build (vue.esm-browser.prod.js) because it includes the template compiler and loads fast. That means the previews do not show [Vue warn] messages. To see them in your own page, swap the file name for the development build, vue.esm-browser.js, from the same folder on the CDN. You will then also see a note in the console that you are running a development build.

flowchart LR
    S["Source code"] --> D["Dev build<br/>warnings, helpful errors,<br/>DevTools, slower"]
    S --> P["Production build<br/>no warnings, minified,<br/>fast and small"]
    D --> A["You debug here"]
    P --> B["Users run this"]

Same code, two builds: all the hand-holding lives in the development build only.

Vue DevTools

The Vue DevTools browser extension (Chrome, Firefox, Edge) adds a Vue tab to the browser's developer tools. It works with apps built in development mode, and you can also run it as a standalone app or a Vite plugin. These are the panels you will use most:

  • Components: the live component tree. Click a component to see its props, ref values, computed values and injected values. You can edit values in place and watch the page react, which is a fast way to test "what if this prop were empty?".
  • Timeline: a time-ordered record of events, component updates, mouse and keyboard events, and performance. It helps answer "what happened right before it broke?" and "why did this component re-render?".
  • Pinia and Router tabs: inspect the current state of every store, replay mutations, and see the current route and its params.
  • Inspect (the target icon): click an element on the page to jump to the component that rendered it.

A common workflow: something looks wrong, you click the element with Inspect, find the component, and look at its props. If the prop value is wrong, the bug is in the parent; if the prop is right but the output is wrong, the bug is in this component. This quickly halves the search area.

Logging reactive state

Reactive objects are Proxies, so console.log(state) often prints something like Proxy(Object) that you have to expand. Better options:

JavaScript
console.log(JSON.parse(JSON.stringify(state)));  // a plain, frozen-in-time copy
console.log(toRaw(state));                        // the underlying plain object
console.log(count.value);                         // for refs, log .value

A plain copy also avoids a classic confusion: the console shows live objects, so expanding a logged object later shows its current contents, not the contents when it was logged. A copy shows the moment you logged it.

Another trick that needs no tools at all: print the state into the template while you work.

HTML
<pre>{{ state }}</pre>

Vue formats it as JSON, and it updates live as the state changes. The second runnable example below uses exactly this idea.

For stepping through code, put a debugger statement in a method or setup() and open the browser's developer tools; execution pauses there and you can inspect every variable. Vite generates source maps in development, so you debug your own code rather than compiled output.

Central error handling

Errors in components do not always reach the console in an obvious place. Vue catches errors thrown in render functions, setup(), event handlers, watcher callbacks and lifecycle hooks, and routes them through one function, which you can replace:

JavaScript
app.config.errorHandler = (error, instance, info) => {
  // error:    the thrown value
  // instance: the component instance where it happened (or null)
  // info:     a string describing where Vue was running your code
};

The info string tells you what kind of code failed. In the development build it is readable text such as "setup function", "render function", "native event handler" or "watcher callback". In the production build, to save bytes, it is a link to Vue's error reference instead, such as https://vuejs.org/error-reference/#runtime-5 (the #runtime-0 code is a setup function, #runtime-1 a render function, #runtime-3 a watcher callback and #runtime-5 a native event handler). This single hook is where you would send errors to a logging service in production, or show a "something went wrong" toast.

The next example registers a handler and triggers an error from three places. Each error ends up in the log instead of crashing the app, and the handler also receives the component's name. Because the preview loads the production build, info appears as a reference link; load the development build to see the readable text.

One place for every error

Click each button and watch the log fill up (the three lines contain #runtime-5, #runtime-3 and #runtime-0). The page keeps working after each error; without the handler, the browser console would show the errors and, in some cases, a half-rendered tree.

Error boundaries with onErrorCaptured

app.config.errorHandler is global. Sometimes you want to catch a failure near where it happens, so a broken widget shows a fallback and the rest of the page stays alive. Vue's tool for this is the onErrorCaptured hook. A component that uses it receives errors from all of its descendants, and returning false stops the error from bubbling further.

flowchart TD
    C["Child throws"] --> P["Nearest parent with onErrorCaptured"]
    P -->|"returns false"| Stop["Handled: bubbling stops"]
    P -->|"returns nothing"| G["Next ancestor with onErrorCaptured"]
    G --> R["app.config.errorHandler"]
    R --> L["Logged or reported"]

Errors travel up the component tree through every onErrorCaptured hook, then reach the app-level handler.

Vue has no built-in error boundary component, but it takes only a few lines to write one:

A reusable error boundary

When the name is removed, user.name.toUpperCase() throws inside Profile's render. The boundary catches it, shows its fallback, and the rest of the page is untouched. The <pre>{{ user }}</pre> line at the bottom is the "print the state" trick from earlier. Because the boundary is keyed on the user data, giving the user a name again creates a fresh boundary and the profile recovers.

Put boundaries around risky or independent areas (a chart, a third-party widget, a route's content), not around every component. Too many boundaries hide real errors.

Decoding common messages

Warnings are written for humans. Here are the ones that show up most often, what they mean, and the usual cure.

Message (start of it) Usual cause Fix
Property "nmae" was accessed during render but is not defined on instance. A typo in the template, or the value was not returned from setup() (or not declared in data). Fix the name; return it from setup(). <script setup> exposes top-level bindings automatically.
Failed to resolve component: MyCard The component was never imported and registered, or the tag name does not match. Import it (and register it, outside <script setup>); check spelling.
Invalid prop: type check failed for prop "count". Expected Number with value 5, got String with value "5". The parent passed a string where a number was declared, such as count="5" instead of :count="5". Bind with : so the value is a JavaScript expression. See Props.
Set operation on key "n" failed: target is readonly. Code assigned to a prop or a readonly object. Copy the value into local state, or emit an event so the parent changes it.
Component is missing template or render function The component has no template or render, or the runtime-only build was used with a string template. Add a template; load a build that includes the compiler (or precompile with a build tool).
Extraneous non-props attributes (class) were passed to component but could not be automatically inherited... A component with several root nodes (or text) received class, id etc. Vue does not know where to put them. Wrap in one root, or bind $attrs yourself. See Fallthrough Attributes.
Maximum recursive updates exceeded in component A watcher or computed side effect keeps changing the state it depends on, causing an endless loop. Break the cycle: do not write to a value from a watcher on that same value unless a condition stops it.
Hydration node mismatch (or similar) Server-rendered HTML differs from what the browser rendered first. Make server and client output identical; see SSR and hydration.

Two silent bugs deserve a mention because no warning accompanies them:

  • Forgetting .value in script code: count++ on a ref does nothing useful; you need count.value++. See Reactive State with ref.
  • Losing reactivity by destructuring a reactive object: const { x } = state copies a number, not a live link. See Reactivity Pitfalls.

When the UI does not update, ask: is this value reactive at all, and did I replace it with a plain copy somewhere?

A debugging routine that works

  1. Read the console. Fix the first warning or error, because later ones are often consequences.
  2. Reproduce small. Find the minimal steps; remove code until the bug disappears, then put back the last piece.
  3. Look at the data. In DevTools, check the props and state of the component. Is the input wrong, or the output?
  4. Narrow it down. Use console.log with a plain copy, a <pre> dump, or a debugger line to see where the value first goes wrong.
  5. Write a test that fails because of the bug (see Unit Testing Components), then fix it.
  6. Check production separately. Some bugs appear only in the minified build, such as a missing import or a difference caused by tree shaking. Build and preview locally (npm run build && npm run preview).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You open your deployed site and the console shows no [Vue warn] messages even though a component has a typo in its template. Why?

    Warnings exist only in the development build. Debug in dev mode to see them.
  2. 2. What does the info argument of app.config.errorHandler tell you?

    Vue passes a description (readable text in development, a link to the error reference in production) so you know where the failure came from.
  3. 3. What does returning false from an onErrorCaptured hook do?

    Returning false marks the error as handled, so it does not bubble further up.
  4. 4. The warning says 'Invalid prop: type check failed for prop "count". Expected Number ... got String'. What is the likely mistake?

    Without the colon, the attribute value is a plain string. With :count it is a JavaScript expression and becomes a number.
  5. 5. Why is console.log(JSON.parse(JSON.stringify(state))) often better than console.log(state) for a reactive object?

    A reactive object is a Proxy, and the console shows its current contents when expanded. A plain copy shows exactly what the data was when you logged it.

Summary

  • Read the console first: [Vue warn] messages name the component and the problem, but only in development builds.
  • Vue DevTools lets you inspect and edit props and state, trace events on the timeline, and check Pinia and the router.
  • Log plain copies (JSON.parse(JSON.stringify(x)) or toRaw) or print <pre>{{ state }}</pre> instead of staring at Proxies.
  • app.config.errorHandler(error, instance, info) is the single place for errors from setup, render, events and watchers.
  • onErrorCaptured makes error boundaries: catch near the failure, show a fallback and return false.
  • Learn the common messages: unknown property, unresolved component, prop type mismatch, readonly writes, missing template.
  • Silent bugs, such as a forgotten .value or destructured reactivity, need you to reason about the data.

Your app works and is debuggable. Now make it fast, starting with Performance Basics.