JAVASCRIPT
Programmatic Scroll to a Specific Element in Vue 3
Discover how to programmatically scroll to any DOM element in Vue 3 using template refs and native JavaScript `scrollIntoView()` for smooth navigation.
<template>
<div>
<p style="height: 1000px;">Scroll down to see the button</p>
<button @click="scrollToElement">Scroll to Target Element</button>
<p style="height: 500px;"></p>
<div ref="targetElement" style="background-color: lightblue; padding: 20px;">
<h2>I am the Target Element!</h2>
<p>You scrolled here programmatically.</p>
</div>
<p style="height: 1000px;">More content below</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const targetElement = ref(null);
const scrollToElement = () => {
if (targetElement.value) {
targetElement.value.scrollIntoView({
behavior: 'smooth', // Optional: for smooth scrolling
block: 'start' // Optional: align the top of the element to the top of the scroll container
});
}
};
</script>
How it works: This snippet demonstrates how to programmatically scroll to a specific DOM element within a Vue 3 component. By attaching a `ref` (e.g., `ref="targetElement"`) to the desired HTML element and then using the `targetElement.value.scrollIntoView()` method, you can smoothly navigate the user's view to that element. This is particularly useful for single-page applications, anchor links, or guiding users through multi-step forms.