我有一个 Map,其中的键是 Vue 组件的实例,例如:
const instanceA = new Vue({...});
const instanceB = new Vue({...});
const register = new Map();
function registerInstance(instance){
register.set(instance, []);
}
如何 Hook Vue 组件销毁的回调?我希望当组件被销毁时,我会从我的 Map
寄存器中删除它的引用。像这样的东西:
function registerInstance(instance){
register.set(instance, []);
instance.onDestroy(() => {
register.set(instance, null);
register.delete(instance);
});
}
这会进行适当的清理以避免内存泄漏,但不确定如何向 Vue 实例的销毁过程添加回调...
我不想在每个组件的 beforeDestroy
或 destroyed
函数中添加此逻辑。我想从组件外部添加它们,只需使用其实例指针...
我考虑过用一个调用我的代码的函数来重写instance.beforeDestroyed,然后调用实例中的原始instance.beforeDestroyed。但这感觉很不对
最佳答案
好的,看起来我们可以使用 instance.$once("hook:beforeDestroy", () => {
向钩子(Hook)添加回调!
一个例子是:
const instance = new Vue({});
instance.$once("hook:beforeDestroy", () => {
console.log('Destroying!');
});
setTimeout(() => {
instance.$destroy();
}, 1000);
<script src="https://vuejs.org/js/vue.min.js"></script>
关于javascript - 向 Vue 实例的 destroy 钩子(Hook)添加回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058864/