Using Expressions with Vue Directives

This entry is part 8 of 40 in the series Vue.js: From Beginner to Professional

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.

Series Navigation<< Introduction to DirectivesIntroduction to Vue Events >>

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *