useToggleScope
A composable for conditionally managing Vue effect scopes based on reactive boolean conditions with automatic cleanup.
Usage
The useToggleScope composable wraps Vue’s effectScope API to create and destroy reactive effect scopes based on a boolean condition. When the condition becomes true, a new scope is created and your callback runs. When false, the scope is stopped and all effects are cleaned up automatically.
<script setup lang="ts">
import { useToggleScope } from '@vuetify/v0'
import { shallowRef, watch } from 'vue'
const isEnabled = shallowRef(false)
const data = shallowRef(0)
const { isActive } = useToggleScope(isEnabled, () => {
// This watch is only active when isEnabled is true
watch(data, (value) => {
console.log('Data changed:', value)
})
})
</script>
<template>
<div>
<button @click="isEnabled = !isEnabled">
{{ isEnabled ? 'Disable' : 'Enable' }} Watcher
</button>
<p>Scope active: {{ isActive }}</p>
<input v-model.number="data" type="number">
</div>
</template>Architecture
useToggleScope wraps Vue’s effectScope for conditional reactive effect management:
Reactivity
| Property/Method | Reactive | Notes |
|---|---|---|
isActive | Computed from scope ref | |
source | WatchSource, triggers scope on/off | |
start() | Create and run the effect scope | |
stop() | Stop and clean up all effects in the scope | |
reset() | Stop then immediately restart the scope |
Examples
The mousemove listener only exists while the scope is active. Starting the scope creates the listener; stopping it removes it automatically via effectScope cleanup.
FAQ
Don’t use it to guard a watcher that must run synchronously when a value changes — creating the scope introduces an async tick, so the watcher can miss the synchronous update. Use a plain conditional inside the watcher instead.
The scope is stopped and every effect registered in it — watchers, useEventListener listeners, and the like — is cleaned up automatically via onScopeDispose. No manual teardown needed.
It stops the current scope and immediately restarts it, re-running your callback in a fresh scope. Useful when you need to rebuild the effects without toggling the source condition off and on.