Created
April 11, 2025 17:59
-
-
Save cn-2k/336de0551101b7e23e64a2bc4e42e475 to your computer and use it in GitHub Desktop.
Scroll to the bottom of a list using Vue's nextTick()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { ref, nextTick } from 'vue'; | |
const items = ref([]); | |
const newItem = ref(''); | |
const itemsList = ref(null); | |
const addItem = async () => { | |
// Add item to list | |
items.value.push(newItem.value); | |
newItem.value = ''; | |
// This won't work immediately | |
console.log('before DOM Update', itemsList.value.scrollHeight); | |
// Wait for DOM update | |
await nextTick(); | |
// Now we can safely access the updated DOM | |
const container = itemsList.value; | |
container.scrollTop = container.scrollHeight; | |
console.log('after DOM Update', itemsList.value.scrollHeight); | |
}; | |
</script> | |
<template> | |
<div> | |
<div ref="itemsList" class="items-container"> | |
<div v-for="item in items" :key="item"> | |
{{ item }} | |
</div> | |
</div> | |
<input v-model="newItem" @keyup.enter="addItem" /> | |
<button @click="addItem">Add Item</button> | |
</div> | |
</template> | |
<style scoped> | |
.items-container { | |
height: 80px; | |
margin-bottom: 5px; | |
border: 1px solid black; | |
padding: 5px; | |
overflow: scroll; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment