主要用途是便于回收监听器(副作用/effects),防止内存泄漏.
一般情况, 在组件的setup中声明的变量和监听器, 随着组件的销毁会自动销毁. 但在组件之外, 这些变量和监听器并没有绑定组件,所以需要手动销毁, 否则它们就会一直存在, 造成内存泄漏.
effectScope 就提供了一个便捷的销毁方式.
例如在封装echarts的过程中, 我们需要监听画布大小/配置项/网页主题等事件, 就可以这样封装:
export function useEcharts(options,renderFun) {
// ...
// 其他业务逻辑
const domRef = ref(null);
const scope = effectScope();
scope.run(() => {
watch([width, height], ([newWidth, newHeight]) => {
// 大小变动
resize()
});
watch(
options,
newValue => {
// 配置变动
update(newValue);
},
{ deep: true }
);
watch(
() => theme.darkMode,
() => {
// 主题变动
updateTheme();
}
);
});
onScopeDispose(() => {
// 销毁
destroy();
scope.stop();
});
return {
domRef
};
网友评论