Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mehany's avatar
Level 13

Correct way to create Vue directives?

In Angular, I used to create directives for the components that would be repeated throughout the application. Angular 1.xhas the following:

 @ reads the attribute value, 
 = provides two-way binding, 
& works with functions

Within the directive, i have the option to add:

templateUrl // Violates Vue JS philosophy - think in components OK!
controller // I need to add something like this to the directive
link  // In angular, this function manipulates the DOM - I get three parameters ( scope, element, attrs  )  so also this one,  to manipulate the DOM 

I like the idea of being able to update the directive DOM based on some user's actions. Furthermore, i see that a Vue directive can have bind , Update & unbind methods but not sure how I can use them to provide similar behavior as Angular directive. Can someone clarify!?

P.S : with Vue components, I can achieve this easily because a component has methods method where I can add all the components functions. Is the same thing possible with a directive?

What I am trying to do is to create generic reusable directives that I could include on the same page. If I am raising the wrong question, how can I achieve this in Vue JS?

ping ping @JeffreyWay

0 likes
3 replies
topvillas's avatar

Don't be fooled by the name, Vue's directives aren't really the same as Angular's. They're really meant for applying behaviour to the DOM. Just use components with props for reusable ... components.

mehany's avatar
Level 13

@topvillas that is what I am getting to. It looks like I will end up creating just components and forget about directives! I am trying something like the below and hopefully I don't run into scope issues!:

  // Bind a Vue component to some element
  // @param element ID
 function createMyFavoriteVueComponent( element.id )
    {
         // vue component code will go here
        new Vue({ 
            el: '#'+element.id
        })
    } 
Juukie's avatar

Remember that components should be declared like this:

var unicorn = Vue.component('unicorn', {
  data: function () { 
    return { message: 'Unicorn!' }
  },
  template: '<div>{{ message }}</div>'
});

The above will create a global component, accessible in evert Vue instance you've created with new Vue({}); If you want a component to only be accessible in a specific Vue instance, do it like this:

new Vue({
  el: '#app',
  template: '<div><unicorn></unicorn></div>',
  components: {
    'unicorn': {
      data: function () { 
        return { message: 'Unicorn!' }
      },
      template: '<div>{{ message }}</div>'
    }
  }
});

Please or to participate in this conversation.