Intuitive Vue Console Logging for Reactive Objects

2023-11-25

During Vue development, we often need to inspect reactive objects (like ref, reactive) in the console. However, the default display of these values is often not intuitive, posing challenges for debugging. This article will introduce how to use Chrome's custom formatters feature to make these objects appear clearer and more understandable in the console.

Problem

As shown in the following image, when we try to print ref, reactive, or shallowRef in a Vue application, the printed results are often not intuitive, making it difficult to recognize the type and structure of the objects at a glance.

Unformatted Vue reactive objects in console log

Using Custom Formatter

Chrome custom formatter allows developers to customize the display of JavaScript objects in Chrome DevTools Console. Vue utilizes this feature to present its reactive objects in the console in a more understandable form.

Formatted Vue reactive objects in console log

Activation Steps

To enable this feature in Vue 3, you DO NOT need to write additional code or install any plugins. Simply follow these steps:

  1. Open Developer Tools in Chrome, and then press F1 to go to the settings page.
  2. Go to Preferences → Console, and check the "Enable custom formatters" option.
  3. Refresh the webpage.

Setting of custom formatters in Chrome

Note: If you want to use the Custom Formatter in the Vue SFC Playground, you need to switch from PROD mode to DEV mode.

Explanation of the Principle

When the Vue 3 dev server starts, it executes initCustomFormatter, which displays Vue objects in DevTools in a more intuitive way, thereby enhancing the developer's debugging experience.

Summary

Using Custom Formatter can provide clearer data representation during development, which is very helpful for developing Vue applications. However, it is important to note that this streamlined output also hides certain underlying data structures. Therefore, when working on development involving Vue's internal mechanisms, it is advisable to temporarily disable this setting as needed.

🎉  Thanks for reading and hope you enjoy it. Feel free to check out my other posts and find me on X and GitHub!