【问题标题】:destroy watch in vnode context in vuejs2在 vuejs2 的 vnode 上下文中销毁 watch
【发布时间】:2019-08-05 04:22:04
【问题描述】:

在指令绑定方法中,有一个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");
    }
});

【问题讨论】:

    标签: javascript vuejs2 vue-directives


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我认为您可以随时取消关注您的依赖关系。

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

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

      【讨论】:

      • 有什么方法可以在 unbind 方法中调用 unwatch 吗?
      • 也许试试这个:this.unbind.unwatchDependency = ...;并在 unbind 中:this.unwatchDependency();
      猜你喜欢
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 2011-10-09
      • 2016-06-18
      • 1970-01-01
      相关资源
      最近更新 更多