Vue Tip: Debugging in Templates


Probably you already tried to add a JavaScript expression like console.log(message)
in your template:
<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:
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:
<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:
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:
<script setup lang="ts">import { ref } from 'vue'const message = ref('Hello World')</script><template> <span>{{ $log(message) || message }}</span></template>
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.