Appearance
Vue useScrollLock Composable
A composable wrapper around ScrollLock (see the web-modals skill) that automatically unlocks when the component is destroyed, preventing the page from getting stuck in a locked state if a modal component is removed unexpectedly.
When to use
Use this composable in any modal or overlay component that needs to prevent background scrolling while open. It automatically unlocks on component unmount and pairs with useInert() for a complete modal open/close sequence.
The pattern
Using useScrollLock()
useScrollLock() returns a ScrollLock instance with lock() and unlock() methods. The composable registers an onUnmounted hook that calls unlock() automatically, so scroll state is always restored even if the component is removed without explicitly closing:
javascript
import { useScrollLock } from "./use-scroll-lock.js";
const lock = useScrollLock();
function openModal() {
lock.lock();
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
lock.unlock();
}Implementing useScrollLock()
The composable creates a ScrollLock instance and hooks into Vue's onUnmounted lifecycle to guarantee cleanup:
javascript
import { onUnmounted } from "vue";
import { ScrollLock } from "./scroll-lock.js";
export function useScrollLock(elementOrSelector = document.scrollingElement) {
const lock = new ScrollLock(elementOrSelector);
onUnmounted(() => lock.unlock());
return lock;
}