JAVASCRIPT
Programmatic Scroll to Element Using Vue Refs
Learn to programmatically scroll to specific HTML elements in Vue 3 applications using template refs, enhancing navigation and user experience.
// ScrollToElement.vue
<template>
<div class="scroll-container">
<h1>Scroll Demo</h1>
<button @click="scrollToSection('section1')">Go to Section 1</button>
<button @click="scrollToSection('section2')">Go to Section 2</button>
<button @click="scrollToSection('section3')">Go to Section 3</button>
<div class="spacer"></div> <!-- Spacer to ensure scrollability -->
<div ref="section1" class="section">
<h2>Section 1</h2>
<p>Content for section 1. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div class="spacer"></div>
<div ref="section2" class="section">
<h2>Section 2</h2>
<p>Content for section 2. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="spacer"></div>
<div ref="section3" class="section">
<h2>Section 3</h2>
<p>Content for section 3. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.</p>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const section1 = ref(null);
const section2 = ref(null);
const section3 = ref(null);
const scrollToSection = (sectionName) => {
const targetSection = {
section1: section1.value,
section2: section2.value,
section3: section3.value
}[sectionName];
if (targetSection) {
targetSection.scrollIntoView({
behavior: 'smooth',
block: 'start' // or 'center', 'end', 'nearest'
});
}
};
</script>
<style scoped>
.scroll-container {
max-height: 400px; /* Make the container scrollable */
overflow-y: auto;
border: 1px solid #ccc;
padding: 10px;
}
.spacer {
height: 300px; /* Push sections apart for clear scrolling */
background: #f0f0f0;
margin: 20px 0;
display: flex;
align-items: center;
justify-content: center;
color: #888;
}
.section {
padding: 20px;
border: 1px solid #eee;
margin-bottom: 20px;
background: #fff;
}
</style>
How it works: This snippet demonstrates how to programmatically scroll to a specific HTML element in a Vue 3 component using template refs. By assigning a `ref` attribute to elements, you can gain direct access to their DOM instances via `ref()` in the `<script setup>`. The `scrollToSection` function then uses the browser's native `scrollIntoView()` method, allowing for smooth scrolling to the target element. This is useful for 'back to top' buttons, internal navigation, or highlighting specific content.