gpt4 book ai didi

javascript - 在 vuejs2 的 vnode 上下文中销毁 watch

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:39 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

关于javascript - 在 vuejs2 的 vnode 上下文中销毁 watch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com