Should I use directive or component

Image

Very often people ask me the question "What is the difference between component and directive and what should I use?".

The short answer is - in 90% cases you want to use component in our application.

When we want to create reusable html or reusable widget with some javascript logic you should create a component. If you need to use the same widget in two different places with the same data - just create a component.

So this question can be simplified to "When should I use custom directive?".

1. To extend element functionality without deeper DOM

If you want to extend element functionality, but you don't want your DOM to get deeper as a result. This can be really important if you are using CSS frameworks where certain DOM structure needed and adding one more wrapper around child will ruin the whole markup.

To understand this just take a look on directives which are going out of the box. For example, v-for directive. It allows you to loop through the collection. That's very useful directive and we really use it in any component that we want and we don't want to make the DOM any deeper which happens with component.

Actually v-for could be a component but this will require deeper DOM every time.

Instead of such construction

<div v-for="item in items">{{item.title}}</div>

We would use something like this

<v-for items="item in items">
  <div>{{item.title}}</div>
</v-for>

2. To implement have multiple functionality with single HTML tag

When you have a single HTML tag that should have multiple functionality. For example, an element should trigger an Ajax request and have a custom tooltip at the same time. As this are two different things, it make sense to split them in two directives and not to implement in single component.

<button v-fetch v-tooltip>Update user data</button>

Just to sum everything up you should use directives as rarely as possible.