vue3.x 副作用管理域effectScope

目的

  • 创建一个管理watcher、computed这样的作用域,以便能够统一|自动卸载依赖
  • 可以脱离组件使用,则类似 unmounted 生命周期

使用

const scope = effectScope()

scope.run(() => {
  const doubled = computed(() => counter.value * 2)

  watch(doubled, () => console.log(doubled.value))

  watchEffect(() => console.log('Count: ', doubled.value))
})


scope.stop()	//停止所有的副作用监听

获取当前活跃的effect scope和执行时所处的scope有关

<script setup>
import {effectScope,ref,onScopeDispose,getCurrentScope} from 'vue'
const setupScope=getCurrentScope() // 有值,因为setup就是在一个effcetScope中

const scope=effectScope();
scope.run(()=>{
  const count=ref(0)
  getCurrentScope() // 为当前scope
  onScopeDispose(()=>{
    console.log('卸载了3')
  })
  return {count}
})

function fn(){
	getCurrentScope() // 没值,click中执行时未处在scope中
}
</script>

<template>
	<div @click='fn'></div>
</template>

监听作用域停止

  • 会在当前作用域以及上级scop作用域被卸载时调用
    • 如果const scope=effectScope(true),那上级作用域销毁时,不会销毁自身,自身作用域内的onScopeDispose不会触发
  • 当组件卸载时会自动调用
  • 通过scope.stop|getCurrentScope().stop()手动调用
  • 每个onScopeDispose只会触发一次
<script setup>

const scope=effectScope();
const s=getCurrentScope(true);

const state=scope.run(()=>{
  const count=ref(0)
  onScopeDispose(()=>{
    console.log('绑定scope卸载') // 如果没有true,则会绑定setup scope和scope一起卸载
  })
  return {count}
})
onScopeDispose(()=>{
  console.log('绑定setup scope卸载了')
})
onScopeDispose(()=>{
  console.log('绑定setup scope卸载了2')
})

</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值