Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroy watch in vnode context in vuejs2

In directive bind method, there is a vnode.context.$watchand 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");
    }
});
like image 397
Anik Saha Avatar asked Oct 17 '22 05:10

Anik Saha


1 Answers

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();
    }
});
like image 164
ATT Avatar answered Oct 21 '22 06:10

ATT