javascript - 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
}
})
如何将我的价值从bind
to传递unbind
?
PS 在我看来唯一的解决方法是修改el
以附加一个 html 属性“my-custom-index”bind
并在unbind
. 但这太hacky了...
解决方案
这似乎是一种使用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!
}
})
推荐阅读
- r - R根据前面的结果逐组计算
- python - 重写一个文件夹中的文件并重命名它们
- angular - 在角度指令中定义 @HostListener 事件的事件顺序
- java - 为什么类名以数字开头?
- javascript - 如何将图像 URL 传递给 React 路由器?图像未显示在组件中,但图像已通过?
- mysql - 为什么 phpmyadmin 连接到 mysql 时出错?
- html - 如何使用包含“_ngcontent-c1”标签的 rvest html 内容进行网络抓取?
- android - 收到通知时获取 java.lang.IllegalAccessError
- python - 问题(已解决):ModuleNotFoundError: No module named 'xzy' after modifying module in google colab
- javascript - 无故获取解析错误 Typescript、Vue、vue-property-decorator、VSCode