In directive bind method, there is a vnode.context.$watch
and every time that directive added to HTML, it is also adding another watcher with previous watcher. Because of that same watchers are calling more than once.
Is there any way to destroy the previous watcher when directive unbind method called.
Vue.directive("dynamic-lookup", {
bind: function (el, binding, vnode) {
let dependency = setValue("dynamic-lookup-dependency");
if (dependency) {
vnode.context.$watch(dependency, function (newVal, oldVal) { }); });
}
},
unbind: function(el, binding, vnode) {
console.log("unbind");
}
});
According to the documentation, the $watch
function it-self returns the unwatch function. You can save the returned function in vnode.context
and call this function in directive unbind hook like this:
Vue.directive("dynamic-lookup", {
bind: function (el, binding, vnode) {
let unwatch = vnode.context.$watch(vnode.context.property, function (newVal, oldVal) {
//Do something
});
});
if(!vnode.context['unwatch'])
vnode.context['unwatch'] = unwatch;
},
unbind: function(el, binding, vnode) {
vnode.context.unwatch();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With