Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variables in custom VueJS directives?

Tags:

vue.js

vuejs2

I've got an error when tried to declare a variable in the usual way like this:

   Vue.directive('my-directive', {
        varA: '', 
        inserted: function(el, binding, vnode){
              this.varA = 'test'; // TypeError: Cannot set property 
                                  // 'varA ' of undefined
        },
    });

TypeError: Cannot set property 'varA ' of undefined

How do you declare variables in Vue directives?

like image 805
Evgeniy Miroshnichenko Avatar asked Jul 12 '17 06:07

Evgeniy Miroshnichenko


People also ask

What are custom directives in VueJS?

Vue. js comes pre-packaged with a number of directives that developers commonly use when working within the framework. Directives such as v-if , v-show , v-on , v-model , v-bind , v-html , and more are all provided for you out-of-the-box. All of these provided directives start with v- .

What are directives Vue?

Directives are used to modify the behavior of our HTML elements which reside in the DOM. In other words, we can say that directives are one of the important parts of the Vue and it is used just like an HTML element's attribute added along with any HTML elements into the Vue template.

How do I register my Vue directive?

To register a custom directive locally, navigate to the component where you want to use the custom directive, and add the method below as part of the Vue Options API: … directives: { focus: { // directive definition inserted: function (el) { el. focus() } } } ...


2 Answers

In Vue directives, when you need to store a value it is generally stored on the element.

Vue.directive('my-directive', {
  inserted: function(el, binding, vnode){
    el.varA = 'test'; 
  },
});

The element is passed in as an argument to each of the lifecycle events in a directive and you can access the value later from el.varA.

like image 65
Bert Avatar answered Nov 15 '22 07:11

Bert


There seems to be 2 ways for this:

  1. According to this comment on github, you may define a stateful directive like this:

    Vue.directive('my-directive', (() => {
        let varA = '';
        return {
            inserted: function(el, binding, vnode){
                varA = 'test'; 
            },
        };
    })());
    
  2. According to a note box on Vue.js docs:

    If you need to share information across hooks, it is recommended to do so through element’s dataset.

    Vue.directive('my-directive', {
        inserted: function(el, binding, vnode){
            el.dataset.varA = 'test'; 
        },
    });
    
like image 32
Hafez Divandari Avatar answered Nov 15 '22 07:11

Hafez Divandari