Vue Js Scroll Div to Bottom:To scroll a div to the bottom in Vue.js, you can use the ref
attribute to reference the div in your component’s template, and then use the $refs
object to access the div’s scroll properties. One way to do this is to set the scrollTop
property of the div to its scrollHeight
property, which will scroll the div to the bottom.
How can you implement automatic scrolling to the bottom of a div using Vue.js?
This code is a Vue.js application that displays a list of messages and a button to scroll to the bottom of the list. The messages are stored in the messages
array in the data
object of the Vue instance. The v-for
directive is used to iterate over the messages
array and display each message in a div
element.
The scrollToBottom
method is called when the user clicks the button. This method uses the $refs
property to get a reference to the scrollable
div that contains the messages, and then sets the scrollTop
property of the div to the scrollHeight
, which scrolls the div to the bottom.
Vue Js Scroll DIv to Bottom Example
<div id="app">
<div class="scrollable" ref="messages">
<div v-for="message in messages" :key="message.id" class="message">{{ message.text }}</div>
</div>
<button @click="scrollToBottom"> scrollToBottom</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
messages: [
{ id: 1, text: 'item 1' },
{ id: 2, text: 'item 2' },
{ id: 3, text: 'item 3' },
{ id: 4, text: 'item 4' },
{ id: 5, text: 'item 5' },
{ id: 6, text: 'item 6' },
{ id: 7, text: 'item 7' },
{ id: 8, text: 'item 8' },
{ id: 9, text: 'item 9' }
],
};
},
methods: {
scrollToBottom() {
const container = this.$refs.messages;
container.scrollTop = container.scrollHeight;
}
},
});
</script>