S Panfilov
S Panfilov

Reputation: 17581

Vue Custom Directives: how to share a variable between hooks?

I want to share a variable among custom directive's hooks.

Example:

Vue.directive('demo',{
  bind: function(el, binding, vnode) {
    const index = setInterval(/* ... */) //I have an "index" here
  },
  unbind: function(el, binding, vnode) {
    clearInterval(index) // I want to use "index" here
  }
})

How can I pass my value from bind to unbind?

P.S. The only workaround in my mind is to modify el in a way to attach an html-attribute "my-custom-index" in bind and to read it in unbind. But it's soooo hacky...

Upvotes: 0

Views: 1282

Answers (3)

S Panfilov
S Panfilov

Reputation: 17581

It seems to be a way to go to use html-attributes:

Vue.directive('demo',{
  bind: function(el, binding, vnode) { 
    //save
    el.setAttribute('x-my-attr', index);
  },
  unbind: function(el, binding, vnode) {
    //read
    const index = el.getAttribute('x-my-attr'); // The value is a string!
  }
})

Upvotes: 1

Bayardo Lopez
Bayardo Lopez

Reputation: 11

The first option is to use el.dataset to store data. This is limited, however, since dataset can only keep strings. What I did was use the el reference as an id to know what data corresponds to what, like so:

const data = []

Vue.directive('example',{
  bind: function(el, binding, vnode) {
    const index = setInterval(/* ... */) //I have an "index" here
    data.push({el, index})
  },
  unbind: function(el, binding, vnode) {
    const dataIndex = data.findIndex(item => item.el === el)
    const { index } = data[dataIndex]
    clearInterval(index) // I want to use "index" here
    data.splice(dataIndex, 1)
  }
})

Upvotes: 1

Singhi John
Singhi John

Reputation: 347

That where the directive definition is must be in a JS module. So why not define your variables in the module. Then read and write it anywhere in the module scope.

like:

let va = 9
Vue.directive('demo',{
  bind: function(el, binding, vnode) {
    va = va + 1
    const index = setInterval(/* ... */) //I have an "index" here
  },
  unbind: function(el, binding, vnode) {
    console.log(va)
    clearInterval(index) // I want to use "index" here
  }
})

Or you can use this.va = 'covid-19' and var va = this.va.

Or el.dataset.

Upvotes: -1

Related Questions