·
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
<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.log app.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 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.