Javascript is required
·
1 min read

Vue Tip: Debugging in Templates

Vue Tip: Debugging in Templates Image

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

App.vue
1<script setup lang="ts">
2import { ref } from 'vue'
3
4const message = ref('Hello World')
5</script>
6
7<template>
8  <span>{{ console.log(message) }}</span>
9</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
1<script setup lang="ts">
2import { ref } from 'vue'
3
4const message = ref('Hello World')
5
6function log(message: string) {
7  console.log(message)
8}
9</script>
10
11<template>
12  <span>{{ log(message) }}</span>
13</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
1import { createApp } from 'vue'
2import './style.css'
3import App from './App.vue'
4
5const app = createApp(App)
6
7app.config.globalProperties.$log = console.log
8
9app.mount('#app')

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

App.vue
1<script setup lang="ts">
2import { ref } from 'vue'
3
4const message = ref('Hello World')
5</script>
6
7<template>
8  <span>{{ $log(message) || message }}</span>
9</template>

Info

The code for this demo is interactively available at StackBlitz:

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

I will never share any of your personal data. You can unsubscribe at any time.