JAVASCRIPT
Programmatically Scroll to a Specific Element with Vue 3 Refs
Guide to programmatically scroll to any DOM element in a Vue 3 application using template refs and the native `scrollIntoView()` method.
// App.vue
<template>
<div class="container">
<h1>Scroll to Element Example</h1>
<nav>
<button @click="scrollToSection('sectionA')">Go to Section A</button>
<button @click="scrollToSection('sectionB')">Go to Section B</button>
<button @click="scrollToSection('sectionC')">Go to Section C</button>
</nav>
<div class="content">
<section ref="sectionA" class="section">
<h2>Section A</h2>
<p>This is the content for Section A. Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
<p v-for="n in 20" :key="n">Placeholder line {{ n }}</p>
</section>
<section ref="sectionB" class="section">
<h2>Section B</h2>
<p>This is the content for Section B. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...</p>
<p v-for="n in 20" :key="n">Placeholder line {{ n }}</p>
</section>
<section ref="sectionC" class="section">
<h2>Section C</h2>
<p>This is the content for Section C. Ut enim ad minim veniam, quis nostrud exercitation ullamco...</p>
<p v-for="n in 20" :key="n">Placeholder line {{ n }}</p>
</section>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
// Create refs for each section
const sectionA = ref(null);
const sectionB = ref(null);
const sectionC = ref(null);
// Map section names to their refs
const sections = {
sectionA,
sectionB,
sectionC,
};
const scrollToSection = (sectionName) => {
const el = sections[sectionName].value;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
</script>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
nav button {
margin-right: 10px;
padding: 10px 15px;
cursor: pointer;
}
.section {
height: 400px; /* Make sections tall enough to scroll */
border: 1px solid #ccc;
margin-bottom: 20px;
padding: 20px;
background-color: #f9f9f9;
border-radius: 8px;
}
</style>
How it works: This snippet demonstrates how to programmatically scroll to specific DOM elements within a Vue 3 application using template `ref`s. Each section element is assigned a unique `ref` attribute (e.g., `ref="sectionA"`). In the script setup, corresponding `ref` variables are created and then referenced within the `scrollToSection` method. When a button is clicked, `scrollToSection` retrieves the DOM element associated with the given `ref` using `.value` and then calls the native `scrollIntoView()` method. The `behavior: 'smooth'` option provides a pleasant animated scroll, and `block: 'start'` ensures the element aligns with the top of the scrollable area. This technique is invaluable for navigation within long pages or single-page applications.