How to declare variables in custom VueJS directives?

Viewed 5581

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?

3 Answers

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'; 
        },
    });
    
Related