I’m sure you noticed by now that we use the v-on and v-bind directives quite a lot in Vue.js. Wouldn’t it be nice if we didn’t have to type that out explicitly every time? Fortunately Vue.js provides shorthand syntaxes for these two directives.
Let’s use a button with a click event listener as an example. Instead of prefixing click with v-on and a colon, we can simply replace the prefix with an @ sign. Therefore we can simply write @click=”expression”.
<button @click="hello">Hello (shorthand)</button>
Clicking both buttons will give the same result.
Similarly, we can shorten the v-bind directive’s syntax as well. The shorthand for this directive is simply a colon followed by the name of the attribute to bind to. In this case, we are binding to the title attribute, so we just write :title=”expression”.
<p :title="title">Hover me (shorthand)</p>
If I hover my cursor over both of these paragraphs, you will see that the result is the same.
While this syntax may look strange and unlike any other HTML markup you have seen before, these attribute names are actually valid HTML attributes, although they won’t actually do anything without Vue.js. Like I said, it may look a bit strange at first, but don’t worry, it is not going to appear in the markup that is rendered once Vue.js is bootstrapped. So if you were to inspect elements containing these attributes, you will not see any sign of them in your browser’s inspector.
So why didn’t I mention this before, you might ask? First of all, I apologize for keeping you in the dark until now, but instead of starting out by using this syntax, it’s good for you to keep in mind that when you are using these shorthand syntaxes, you are in fact using the v-on and v-bind directives. This makes it easier to understand what actually happens when using these shorthand syntaxes, instead of just using them and not knowing what actually happens behind the scenes.
That being said, these shorthand syntaxes are the most common way to use the two directives, so this is also the syntax that you will see me use for the rest of this course.
This completes the walkthrough of the fundamentals of Vue.js, and thereby this section of the series. Of course there are more fundamental concepts of Vue.js such as components and forms, but subjects like these are quite big and will therefore have their own dedicated sections.
Learn Vue.js today!
Take an online course and become an Vue.js champion!
Here is what you will learn:
- How to build advanced Vue.js applications (including SPA)
- How Vue.js works under the hood
- Communicating with services through HTTP
- Managing state of large applications with Vuex
- ... and much more!