In the previous recipe, we had a complete overview of filters and we said that Vue comes with no built-in filters except for an equivalent of the JSON filter. This filter was very useful and, while its considered not really orthodox to debug with it, sometimes it just makes your life easier. Now we have it straight away without even writing it.
To see it in action, we can simply display the value of an object in our Vue instance.
- Write the following JavaScript:
new Vue({ el: '#app', data: { cat: { sound: 'meow' } } })
This just creates a cat
object in our code with a string inside.
- Write the following HTML:
<p>Cat object: {{ cat }}</p>
- Run your app and notice how the
cat
object is outputted in all it's beauty, just likeJSON.stringify
.
Cat will display the content of the cat
object. In the old Vue, to get this result we had to write {{ cat | json }}
.
A thing to be wary of is loops in our objects. If our object contains a circular reference, and you wrap it in mustaches, this will not work. These objects are more common than you would think. HTML elements, for example, are JavaScript objects that contain references to a parent node; the parent node in turn contains a reference to its children. Any such tree structure would cause the mustaches to print an infinite description of the object. When you actually do it, Vue simply throws an error and refuses to work. The error you would see in the console is actually thrown by the internal method used to print the JSON.stringify
object.
A practical situation in which using mustaches could be useful is when the same value is changed in several places, or when you want to quickly check the content of a variable. Mustaches can be useful even for demonstrational purposes, as it's clear from the usage you will see in this book.