Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Debugging in Templates

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Feb 16, 2023
1 min read
|
24 views
Template
Debugging
Vue Tip: Debugging in Templates Image
New Vue & Nuxt tips delivered to your inbox:

Probably you already tried to add a JavaScript expression like console.log(message) in your template:

App.vue
<script setup lang="ts">import { ref } from 'vue'const message = ref('Hello World')</script><template>  <span>{{ console.log(message) }}</span></template>

Your app will throw the following error:

Uncaught TypeError

Cannot read properties of undefined (reading 'log')

It does not work because console is not available on the component instance. A quick fix would be to add a log method to the component:

App.vue
<script setup lang="ts">import { ref } from 'vue'const message = ref('Hello World')function log(message: string) {  console.log(message)}</script><template>  <span>{{ log(message) }}</span></template>

Of course, you don't want to add that function to every component you want to debug. Therefore let's add console.log to the global properties that can be accessed on any component instance inside your application:

main.js
import { createApp } from 'vue'import './style.css'import App from './App.vue'const app = createApp(App)app.config.globalProperties.$log = console.logapp.mount('#app')

Finally, you can use $log in every one of your components:

App.vue
<script setup lang="ts">import { ref } from 'vue'const message = ref('Hello World')</script><template>  <span>{{ $log(message) || message }}</span></template>
Info

The code for this demo is interactively available at StackBlitz:


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.