在 vuejs2 的 vnode 上下文中销毁手表

destroy watch in vnode context in vuejs2

在指令绑定方法中,有一个 vnode.context.$watch 并且每次该指令添加到 HTML 时,它也会添加另一个观察者和前一个观察者。因为同样的观察者不止一次地打电话。

有没有办法在调用指令解除绑定方法时销毁之前的观察者。

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

我想你可以在需要的时候解除依赖。

文档 vm.$watch returns 一个停止触发回调的 unwatch functionhttps://vuejs.org/v2/api/#vm-watch

var unwatch = vnode.context.$watch(dependency, function (newVal, oldVal) {
});
// later, teardown the watcher
unwatch()

根据 documentation$watch 函数本身 returns unwatch 函数。您可以将返回的函数保存在 vnode.context 中,并在指令解除绑定钩子中调用此函数,如下所示:

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