VueJS - Easy (2-liner) to scroll to specific element using VueJS and no external libraries
This is my answer to a question on StackOverflow: https://stackoverflow.com/a/57661780/4826740
by Max Poshusta
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button v-on:click="scrollToElement()">
Scroll to first element with class of .index-50
</button>
<button v-on:click="scrollToElement({behavior: 'smooth'})">
Smooth scroll to first element with class of .index-50
</button>
<ul v-for="(item, index) in items" :class="`index-${index}`">
<li>{{ item }}</li>
</ul>
</div>
JavaScript
// See this post on StackOverflow:
// https://stackoverflow.com/a/57661780/4826740
var vm = new Vue({
el: '#app',
data: {
items: []
},
methods: {
scrollToElement(options) {
const el = this.$el.getElementsByClassName('index-50')[0];
if (el) {
el.scrollIntoView(options);
}
},
populate: function() {
for(var i = 0; i<100; i++) {
this.items.push("Item #"+i);
}
}
}
});
vm.populate();