Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8 - Effect作用域 API #2707

Open
666p opened this issue May 6, 2024 · 0 comments
Open

8 - Effect作用域 API #2707

666p opened this issue May 6, 2024 · 0 comments

Comments

@666p
Copy link

666p commented May 6, 2024

// 你的答案
<script setup lang="ts">
import { ref, computed, watch, watchEffect, effectScope, } from 'vue'

const counter = ref( 1 )
const doubled = computed( () => counter.value * 2 )

// 使用 `effectScope` API 使这些Effect效果在触发一次后停止
const scope = effectScope()

// 第一种方法,开启监听后立即注销监听
const stop1 = watch( doubled, () => {
    console.log( 'watch:', doubled.value )
    stop1()
} )
const stop2 = watchEffect( () => {
    console.log( 'watchEffect: ', doubled.value )
    stop2()
}, { flush: 'post' })

// 第二种方法,在下次更新前调用stop方法注销run函数里面的监听方法
scope.run(() => {
    watch( doubled, () => {
        console.log( 'watch:', doubled.value )
    } )
    watchEffect( () => {
        console.log( 'watchEffect: ', doubled.value )
    })
})
counter.value = 2
setTimeout( () => {
    scope.stop()
    counter.value = 4
} )

</script>

<template>
    <div>
        <p>
            {{ doubled }}
        </p>
    </div>
</template>
@666p 666p closed this as completed May 6, 2024
@666p 666p reopened this May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant