I have a vue component with
<form @keydown="console.error($event.target.name);"> gives
app.js:47961 [Vue warn]: Property or method "console" is not defined on the instance but referenced during render.
window.console doesn't work either
What is the proper way to use console and window in a template to debug?
09 Answers
If you want to run it inline instead of using a method, just add this to the form:
<form action="/" @keydown="this.console.log($event.target.name)"> First: <input type="text" name="fname"><br> Second: <input type="text" name="fname2"><br> </form> But it'd be better to use a method instead of running functions inline, so you have more control over it:
<!-- Don't forget to remove the parenthesis --> <form action="/" @keydown="debug"> First: <input type="text" name="fname"><br> Second: <input type="text" name="fname2"><br> </form> ... methods: { debug (event) { console.log(event.target.name) } } 5Simplest way of providing global objects to the template is to place them in computed, like this:
console: () => console. Same goes for window,
computed: { console: () => console, window: () => window, } See it here.
11You can use $el.ownerDocument.defaultView.console.log() inside your template
Pro: Doesn't require any component changes
Con: Ugly
Also if you want to access console from {{ }} you can use global mixin:
Vue.mixin({ computed: { console: () => console } }) If using Vue 3, do:
const app = createApp(App) app.config.globalProperties.$log = console.log If using Vue 2, do:
Vue.prototype.$log = console.log Use $log inside template:
<h1>{{ $log(message) }}</h1> To not interfere with the rendering, use $log with ?? (or || if using Vue 2, since ?? is not supported in the template):
<h1>{{ $log(message) ?? message }}</h1> I'd make a getter for console template variable:
get console() { return window.console; } You can use this.console instead console or wrap call to console in a method, i am using eslint config with rule 'no-console': 'off'
You can use computed property or methods for this case. If you need to code it as javascript in the Vue template. you have to define console in the data.
Please check the code below.
data(){ return { selected :"a", log : console.log } } <span>{{log(selected)}}</span> This will make functionality of console.log available, while resolving the template.
For Vue 3, SFC Composition API, you have to define a function and call console or alert inside that function
<script setup> import Child from "./Child.vue"; function notify(message) { alert(message); } </script> <template> <Child @some-event="notify('child clicked')" /> </template>