Using Expressions with Vue Directives

Published on February 10, 2017 by

Remember how we can embed simple JavaScript expressions within the string interpolation syntax? Well, we can actually do the same with directives. Without further ado, let’s see an example of using an expression.

So I have added a Vue instance in advance which simply contains my full name in two data properties, and a div element which just contains some text. What I want to do now, is to use the v-bind directive to bind an expression to the title attribute. The expression is simply going to concatenate the two data properties.

<div v-bind:title="firstName + ' ' + lastName">Hover to see my name</div>

The expression is a plain JavaScript expression which accesses the data properties that we have defined on the Vue instance.

What’s very interesting, is that Vue.js automatically keeps track of which properties a given expression depends on. If one of the dependencies are updated, the directive is refreshed, i.e. the expression is re-evaluated. Now that’s pretty cool, isn’t it?

While you can indeed add expressions within your template, you should avoid putting too much logic in there. It’s fine to use expressions, but you should try to keep them simple – otherwise you are better off placing the code within a method on the Vue instance instead.


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!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.