Debugging Templates in Vue.js

#Vue#Devtools

Let’s end this Vue Tips Overload with a tip from Rubén Valseca. He’s a co-organizer of VueJS Madrid and Frontfest, as well as a web developer and Vue.js instructor. But among all, he’s one of the nicest persons and friends I know!

He’s also coming to talk to the Vue Day, so make sure you’re not missing out!


The Vue.js DevTools are awesome to inspect your Vue app but sometimes you might want to debug things that are happening in your template and as you heard that you can place JavaScript expressions there maybe you’ve tried to place a console.log and find this situation:

This is due that everything that you placed in the template Vue try to find it in the instance so a quick solution could be put a log method in the component to allow Vue to find it:

and just use {{ log(message) }}.

But this is something that you occasionally want in some different components and it’s a little boring to repeat this code all the time so what can we do is to add an instance property and use the Vue.prototype to place our custom log method in the main.js:

so now we can use $log in every component template and if we don’t want to interfere with the rendering just use the JS lazy evaluation with an OR operator 😊

awesome, right? :D but… what if we want to place a breakpoint in order to quietly debug some variables around the template?

If we place a debugger in the template we might find this:

it is not even compiling the template! 😱 and if we apply the same strategy than before we will find us alone in the prototype function instead of the template that we want to debug​:

​ so in order to place a breakpoint in the middle of the template we can use a little trick wrapping the debugger in an IIFE (Immediately Invoked Function Expression) like this:​

and we will find ourselves in the middle of the compiled render function​:

where in this case the “_vm” variable

means ViewModel

and is the instance of our component :). This is also interesting to check the compiled template but for some reason the variables are not available in the function scope of the chrome devtools until we place them after the debugger:​

and now you can enjoy inspect everything around!

That’s all! I hope that with these tips you will find yourself more confident debugging Vue templates and also enjoy inspecting the insides of the compiled render functions just for curiosity​.

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.