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:
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.log
app.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>
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Nuxt Tip: Rendering Modes
Vue Tip: Use Scoped Slots in a Child Component to Provide Data for Parent Component