英文:
Is it possible to remove an onBeforeUnmount lifecycle hook?
问题
我想在组件卸载时进行一些清理工作,我认为注册和取消注册onBeforeUnmount钩子可能是一种方法。根据文档,我没有看到取消注册onBeforeUnmount生命周期钩子的方法。
我知道我可以设置自己的onBeforeUnmount清理管理,但如果Vue可以很好地完成,我更喜欢使用Vue而不是自己实现。有人知道Vue是否可以取消注册钩子吗?
英文:
I want to do some cleanup when a component is unmounted and I thought that registering and unregistering onBeforeUnmount hooks could be a way to do it. Per the documentation, I don't see a way to unregister onBeforeUnmount lifecycle hooks.
I know I can set up my own at-onBeforeUnmount-cleanup management, but if Vue can do it nicely, I'd prefer Vue over rolling my own. Anyone know if Vue can unregister hooks?
答案1
得分: 1
在评论中,楼主澄清了他想要清除例如间隔的资源...
所以首先,程序员释放资源的推荐钩子是 unmounted
钩子:
https://vuejs.org/api/options-lifecycle.html#unmounted
如果你在 beforeunmounted
中这样做,你的 DOM 仍然存在,释放可能会影响它并引入不希望的潜在副作用,包括屏幕上的抖动,这对用户体验不好。
但是手动释放资源始终是一个糟糕的主意,因为有时会被忘记。
幸运的是,Vue 允许我们将资源包装在一个可组合的函数中:
import { onUnmounted } from 'vue';
export function useInterval(...args) {
const id = setInterval(...args);
onUnmounted(() => clearInterval(id));
}
然后使用它:
<script setup>
import { ref } from 'vue';
import { useInterval } from './useInterval';
const toggle = ref(false);
let num = 0;
useInterval(() => {
toggle.value = !toggle.value;
$log.insertBefore(document.createElement('div'), $log.children[0]).textContent = 'interval #' + num++;
}, 300);
</script>
<template>
<div :style="{background: toggle ? 'yellow' : 'blue'}"></div>
</template>
<style scoped>
div {
transition: background-color .15s;
width: 200px;
height: 50px;
border-radius: 4px;
}
</style>
英文:
The OP clarified in the comments that he wants to clear for example an interval..
So first, the recommended hook for freeing allocated by a programmer resources is the unmounted
hook:
https://vuejs.org/api/options-lifecycle.html#unmounted
If you do that in in beforeunmounted
your DOM is still present and the freeing could affect it and introduce unwanted potential side-effects including jittering on the screen which is bad for UX.
But freeing resourses manually is always a BAD idea because it's sometimes forgotten.
Fortunately Vue allows us to wrap resources in a composable:
import {onUnmounted} from 'vue';
export function useInterval(...args){
const id = setInterval(...args);
onUnmounted(() => clearInterval(id));
}
And use it:
<script setup>
import {ref} from 'vue';
import {useInterval} from './useInterval';
const toggle = ref(false);
let num = 0;
useInterval(() => {
toggle.value = !toggle.value;
$log.insertBefore(document.createElement('div'), $log.children[0]).textContent = 'interval #' + num++;
}, 300);
</script>
<template>
<div :style="{background: toggle ? 'yellow' : 'blue'}"></div>
</template>
<style scoped>
div{
transition: background-color .15s;
width:200px;
height:50px;
border-radius: 4px;
}
</style>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论