首页 > 解决方案 > Vue 自定义指令:如何在钩子之间共享变量?

问题描述

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

例子:

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

如何将我的价值从bindto传递unbind

PS 在我看来唯一的解决方法是修改el以附加一个 html 属性“my-custom-index”bind并在unbind. 但这太hacky了...

标签: javascriptvue.jsvuejs2vue-directives

解决方案


这似乎是一种使用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!
  }
})

推荐阅读