Vue自定义指令:如何在钩子之间共享变量?

时间:2020-05-07 10:52:39

标签: javascript vue.js vuejs2 vue-directives

我想在自定义指令的钩子之间共享一个变量。

示例:

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
  }
})

如何将我的值从bind传递到unbind

P.S。我唯一的解决方法是修改el,以便在bind中附加html属性“ my-custom-index”并在unbind中读取它。但这太糟糕了...

1 个答案:

答案 0 :(得分:0)

指令定义所在的位置必须在JS模块中。那么,为什么不在模块中定义变量。然后在模块作用域的任何位置读取和写入它。

喜欢:

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
  }
})

或者您可以使用this.va = 'covid-19'var va = this.va

el.dataset