9阅网

您现在的位置是:首页 > 知识 > 正文

知识

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

admin2022-11-07知识17

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

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

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

我如何将我的值从 bindunbind?

P.S.在我看来,唯一的变通方法是修改 el 的方式来附加html属性 "my-custom-index "在 bind 并将其读成 unbind. 但这太黑了......



【回答】:

这似乎是一个 去吧 来使用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!
  }
})
【回答】:

指令的定义必须在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.